This are three ways to get n
bytes, expressed as 2*n
Hexadecimal digits:
#!/bin/bash
n=64
# Read n bytes from urandom (in hex).
xxd -l "$n" -p /dev/urandom | tr -d " \n" ; echo
od -vN "$n" -An -tx1 /dev/urandom | tr -d " \n" ; echo
hexdump -vn "$n" -e ' /1 "%02x"' /dev/urandom ; echo
Reading from urandom (and Please, do use urandom).
The hex digits may be redirected to a file or stored in a variable:
a="$(xxd -l "$n" -p /dev/urandom)"
And you could get the original bytes using xxd, as simple as:
## Warning, this produces binary values
echo "$a" | xxd -r -p # If the Hex digits are in a variable.
xxd -r -p "$rndfile" # If the Hex digits are in a file.
If xxd is not available, and assuming the hex digits are in $a
.
You could use this bash code:
#!/bin/bash
>"$rndfile" # erase the file
for (( i=0; i<${#a}/2; i++ )); do # do a loop over all byte values.
# convert 2 hex digits to the byte unsigned value:
printf '%b' $(printf '\\0%o' "0x${a:$i*2:2}") >> "$rndfile"
b="${b#??}" # chop out two hexadecimal digits.
done
Or you may try this sh compatible code (should run in bash comfortably).
Yes it should be sh compatible. Report if you find problems.
Only tested in dash (but should run in some others).
#!/bin/sh
i=$((${#a}/2)) # The (length of $a ) / 2 is the number of bytes.
b="$a" # use a temporal variable. It will be erased.
: >"$rndfile" # erase file contents
while [ $i != 0 ]; do
# Write one byte transformed to binary:
printf '%b' $(printf '\\0%o' "0x${b%"${b#??}"}") >> "$rndfile"
b="${b#??}" # chop out two hexadecimal digits.
i=$((i-1)) # One byte less to finish.
done
bash
andksh
(among others), even on Solaris, provide$RANDOM
, which you can use for a random integer between zero and one less than a modulus. For example,$[${RANDOM}%5]
will resolve to a random number between 0 and 4, inclusive. Note thatsh
does not provide$RANDOM
. – DopeGhoti Nov 23 '15 at 23:20