Search code examples
linuxbashrandom

Using "$RANDOM" to generate a random string in Bash


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?


Solution

  • 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