I am trying to build a random character generator in a bash script on osx 10.8.5 . The goal is to generate random character strings for a script generating salts for the wor
Try a simpler case:
function rand_char {
take=$(($RANDOM % 2)); i=0; echo a b | while read -d\ char;
do
[ "$i" = "$take" ] && echo "$char\c";
((i++));
done
}
It will produce a
and blanks, but no b
.
We can further reduce the problem down to:
echo a b | while read -d\ char; do echo "$char"; done
which only writes a
and not b
. This is because you instruct read
to read up to a space, and there's no space after b
so it fails. This means that one out of every 88 chars will be dropped, causing your lines to be slightly shorter.
The simplest fix is to add a dummy argument to force a space at the end:
echo {a..z} {A..Z} {0..9} (etc etc) \} \| \> \< '' | while read ...
# Here ---^
Note that your method just adds 15 bits of entropy to the salt, while the absolute minimum should be 64. The significantly easier and more secure way of doing this would be:
LC_CTYPE=C tr -cd 'a-zA-Z0-9,;.:_#*+~!@$%&()=?{[]}|><-' < /dev/urandom | head -c 64
(note: this replaces your unicode paragraph symbol with an ascii @)