bash substring weirdness

bash, substring

Solution

You should quote the string to echo:

...
echo -n "${ascstring:$[ 0x$v % $asclen]:1}"

Problem

Here is a fragment of a password generator: ``` # ... ascstring='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHILKLMNOPQRSTUVWXYZ!#$%&()*+-; <=>?@^_`{|}~' asclen=${#ascstring} # modulo ascstring #... r=$(openssl rand 100000 | sha1sum) # generates 40 hex sequence #... for i in {0..38..2} do v=${r:i:2} ; echo -n ${ascstring:$[ 0x$v % $asclen]:1} done echo # ... ``` It uses various definitions of `ascstring` but the one shown causes a problem occasionally. Mostly it's okay: ``` $ ./password-gen.sh `?OCw&a|746|SRm8b&c= $ ./password-gen.sh eE?R%3NdUjSpd<)wPuBV $ ./password-gen.sh 0X8)p8hPobt$x@iGy?!I $ ./password-gen.sh P7LD;p<^lX1d87;{V4S$ ``` But occasionally: ``` $ ./password-gen.sh 5w@$ypassword-gen.sh@)A|l`06B(50f7 ``` If I remove the `*` from `ascstring` this never seems to happen. I wonder what's going on and how I can get around this problem (without reducing the entropy)? Thanks.

Original source