Using "$RANDOM" to generate a random string in Bash
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=abcd1234ABCDfor i in {1..8} ; do echo -n "${chars:RANDOM%${#chars}:1}"doneecho
For those looking for a random alpha-numeric string in bash:
LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 64
The same as a well-documented function:
function rand-str { # Return random alpha-numeric string of given LENGTH # # Usage: VALUE=$(rand-str $LENGTH) # or: VALUE=$(rand-str) local DEFAULT_LENGTH=64 local LENGTH=${1:-$DEFAULT_LENGTH} LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c $LENGTH # LC_ALL=C: required for Mac OS X - https://unix.stackexchange.com/a/363194/403075 # -dc: delete complementary set == delete all except given set}