Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

random

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?

like image 906
Dimareal Avatar asked Sep 09 '15 16:09

Dimareal


1 Answers

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
like image 105
choroba Avatar answered Sep 25 '22 09:09

choroba