I have this script to generate $1 digit(s) of mixed random char from the defined charlists as arrays.
#!/bin/bash
charlist1=(a b c d e f g h i j k l m n o p q r s t u v w x y z)
charlist2=(0 1 2 3 4 5 6 7 8 9)
charlists=(${charlist1[*]} ${charlist2[*]})
i="1"
while [ $i -le $1 ]; do
out=$out`echo -n ${charlists[$(($RANDOM % ${#charlists[*]}))]}`
i=$(( i + 1 ))
done
echo $out
It runs fine in bash, but then if I invoke it with zsh by zsh that_script_above.sh 6
it just generates 6 digit of some same character like this:
>>> zsh that_script_above.sh 6
llllll
>>> zsh that_script_above.sh 6
bbbbbb
And if I modified that script to be like this:
#!/bin/bash
charlist1=(a b c d e f g h i j k l m n o p q r s t u v w x y z)
charlist2=(0 1 2 3 4 5 6 7 8 9)
charlists=(${charlist1[*]} ${charlist2[*]})
i="1"
while [ $i -le $1 ]; do
echo -n ${charlists[$(($RANDOM % ${#charlists[*]}))]}
i=$(( i + 1 ))
done
echo
it works well as I desired for both bash
and zsh
.
So, here is my questions:
- Can someone explain to me about my problem with zsh bash behaviour stated above?
- And how can I use for loop in bash with customizable variable? because it seems
for i in {1..$1}
doesn't work in bash.
bash
/zsh
/ksh
pseudo random number generators are not cryptographically secure, they shouldn't be used to generate secrets. – Stéphane Chazelas Sep 26 '18 at 10:21ls
in some folder, i can get unique id... – user312781 Sep 26 '18 at 11:35mktemp
command just for that:dir=$(mktemp -dp . myprefixXXXXXX)
would create a (private) unique directory in the current directory with that template and store it in$dir
. Comparing withls
is racy. It's better to attempt the mkdirs until it succeeds. Beware of symlinks as well! All those issues are handled properly bymktemp
. – Stéphane Chazelas Sep 26 '18 at 12:03for ((i=1; i<="$1"; i++)); do ...
-- see https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs – glenn jackman Sep 26 '18 at 13:57