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))
2319
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 of a given length. (Default of 22 characters).
function _random_password() {
local l=22
[ -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
if [ $? -ne 0 ] ; then
>&2 echo "Failed to generate a password. Exiting."
exit 1
fi
}
# Generate password, and save to file.
_random_password > password.txt
# Long password
_random_password 120 > long_password.txt
# Password between 20 and 40 characters
_random_password 20 40 > variable_length_password.txt
# Save to a variable.
password="$(_random_password)"
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]}"
Or a random line from a file:
# 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