Random Hex

The randomdhex Function

This an alias function to output a random hexadecimal number. There are many ways to do this but I took this from a StackOverFlow answer.

The Function Header

I'm going to create a function named randomhex that takes one optional argument named digits.

function randomhex -d "random hex string" --argument-names digits

Argument Check

The first thing to do is to check if the user passed in an argument and handle it if they did or use a default if they didn't.

Check For An Argument

The first check uses the test command to see if the user passed in an argument. the -n flag tells it to check if there's a string with one or more characters in it in our digits variable.

if test -n "$digits" # then an argument was passed in

Check If The Argument Is An Integer

If the user did pass in an argument but it can't be coerced to be an integer then our function won't work right so we need to see if the argument is made up of nothing but digits using the string match command and a regular expression to make sure it's only made up of one or more digits.

if test (string match --regex "^[0-9]+\$" $digits)

Set the Argument Value

If the argument was an integer then we'll set the BYTES variable to half of whatever the user passed in, because each byte is represented by two hexadecimal digits (8 bits gives values from 0 to 255 in decimal, 00 to FF in hexadecimal). The argument is a string so we need to pass our division expression ($digits/2) to the math command in order for it to be evaluated as a number. Additionally, the division operator will return a float if the user's input isn't evenly divisible so I'll use the ceil argument to round up to the nearest integer.

set BYTES $(math ceil $digits/2)

Error Message

If the user passed in an argument but it doesn't look like an integer then we'll output a help message. I got the idea of using printf this way from this StackOverflow answer.

  • Each line after the first gets passend into the first string, substituted where %s is
  • One backslash continues the input
  • Two backslashes with a space in-between them will insert an extra line and continue the input
  • The space between the backslashes is important - fish will throw an error if you put \\ instead of \ \
else # the argument isn't an integer
  printf "\t%s\n" \
   "Output a random hexadecimal number" \ \
   "Usage:" \ \
   "randomhex <digits>" \ \
   "Optional argument:" \
   " - Number of digits (will round up to even number)" \
   "   Argument must be an integer (default=8)."
   return
end # if is-integer check

Use The Default

If the user didn't pass in an argument then use a default of 8 hexadecimal digits.

else # Set our bytes so we have 8 digits (double the bytes)
  set BYTES 4
end # setting the number of bytes

Output the Random Hexadecimal

Finally we output the random hexadecimal number that openssl generates.

echo $(openssl rand -hex $BYTES)

Sources