I am trying to write a script to get a random, even hex number. I have found the the openssl command has a convenient option for creating random hex numbers. Unfortunately, I need it to be even and my script has a type casting error somewhere. Bash thinks that my newly generated hex number is a string, so when I try to mod it by 2, the script fails. Here is what I have so far:

hexVal="$(openssl rand -hex 1)"
while [ `expr $hexVal % 2` -ne 0 ]
    hexVal="$(openssl rand -hex 1)"

I have tried various other combinations as well, to no avail. If someone could tell me what is wrong with my syntax, it would be greatly appreciated.


Using bash

To generate an even random number in hex:

$ printf '%x\n' $((2*$RANDOM))


$ hexVal=$(printf '%x\n' $((2*$RANDOM)))
$ echo $hexVal

To limit the output to smaller numbers, use modulo, %:

$ printf '%x\n' $(( 2*$RANDOM % 256 ))

Using openssl

If you really want to use a looping solution with openssl:

while hexVal="$(openssl rand -hex 1)"
    ((0x$hexVal % 2 == 0)) && break

The 0x signals that the number which follows is hex.

Rules for casting numbers in bash

From man bash:

Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater< than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35. [Emphasis added]

  • I decided to stick with the while loop. Thanks much for the help, works as desired.
    – resu
    Jun 17 '16 at 23:48

What about this instead

printf "%0x\n" $(( ($RANDOM*2) & 0xff))

while (( 16#$hexVal % 2))
    hexVal=$(openssl rand -hex 1)

printf "%x [%d]\n"  0x$hexVal  0x$hexVal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.