Proper type casting in a shell script for use with while loop and modulus Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Proper type casting in a shell script for use with while loop and modulus without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 '%xn' $((2*$RANDOM))


$ hexVal=$(printf '%xn' $((2*$RANDOM)))
$ echo $hexVal

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

$ printf '%xn' $(( 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]

We are here to answer your question about Proper type casting in a shell script for use with while loop and modulus - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji