I am trying to use the Bash variable $RANDOM
to create a random string that consists of 8 characters from a variable that contains integer and alphanumeric digits, e.g., var="abcd1234ABCD"
.
How can I do that?
Use parameter expansion. ${#chars}
is the number of possible characters, %
is the modulo operator. ${chars:offset:length}
selects the character(s) at position offset
, i.e. 0 - length($chars) in our case.
chars=abcd1234ABCD
for i in {1..8} ; do
echo -n "${chars:RANDOM%${#chars}:1}"
done
echo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With