Random Numbers and Strings in Bash Shell and Scripting

Creating Random Numbers and Strings in Bash is fairly simple.

Random number in a Range

Using shuf we can do this to get one between 0 and 100

shuf --random-source=/dev/urandom -i 0-100 -n 1

Or simply use RANDOM to generate a number between X and Y

$((RANDOM%Y+X))

As an example

echo $((RANDOM%7200+600))
 -> 1379

Random String

To generate a random string (without special characters):

# get a random string (default 15). Optionally set a random length.
# random_string        -> 15 chars
# random_string 50     -> 50 chars
# random_string 20 80  -> will be between 20 and 80 chars long
random_string() {
        local l=15
	[ -n "$1" ] && l=$1
        [ -n "$2" ] && l=$(shuf --random-source=/dev/urandom -i $1-$2 -n 1)
      	tr -dc A-Za-z0-9 < /dev/urandom | head -c ${l} | xargs
}

Modified from here

Random Password

Generate a random password

choose() { echo ${1:RANDOM%${#1}:1} $RANDOM; }
pass="$({ choose '!@#$%^\&'
  choose '0123456789'
  choose 'abcdefghijklmnopqrstuvwxyz'
  choose 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  for i in $( seq 1 $(( 4 + RANDOM % 8 )) )
     do
        choose '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
     done
 } | sort -R | awk '{printf "%s",$1}')"

From here

Get a Random Line

Using bash arrays, we can get a random line or file:

# Get the file list
files=(/dir/*.txt)
# Find out how many files we have
n=${#files[@]}
# Grab a random one
random_file="${files[RANDOM % n]}"
# Load the file contents
file_contents="$(cat /dir/file.txt)"
# Find out how many lines we have
n=${#file_contents[@]}
# Grab a random line
random_line="${file_contents[RANDOM % n]}"

Source: CyberCiti