How to generate random number in Bash?

Learn how to generate random number in bash? with practical examples, diagrams, and best practices. Covers bash, shell, random development techniques with visual explanations.

Generating Random Numbers in Bash: A Comprehensive Guide

Abstract illustration of random numbers being generated, with dice and binary code elements

Learn various methods to generate random numbers in Bash, from basic integers to cryptographically secure values, and understand their use cases.

Generating random numbers is a common requirement in shell scripting for tasks such as creating temporary filenames, simulating events, generating passwords, or implementing simple games. Bash provides several built-in mechanisms and external commands to achieve this. This article will explore the most common and effective ways to generate random numbers, discussing their strengths and appropriate use cases.

Using $RANDOM for Pseudo-Random Integers

The simplest way to generate a pseudo-random integer in Bash is by using the built-in variable $RANDOM. This variable returns a different pseudo-random integer each time it is referenced. The range of numbers generated by $RANDOM is typically between 0 and 32767 (inclusive), as it's a 16-bit unsigned integer. It's important to note that $RANDOM is not cryptographically secure and should not be used for security-sensitive applications.

echo $RANDOM

# Generate a random number between 1 and 100
RANDOM_1_100=$(( $RANDOM % 100 + 1 ))
echo "Random number (1-100): $RANDOM_1_100"

# Generate a random number between 50 and 150
MIN=50
MAX=150
RANGE=$(( MAX - MIN + 1 ))
RANDOM_MIN_MAX=$(( $RANDOM % RANGE + MIN ))
echo "Random number (50-150): $RANDOM_MIN_MAX"

Examples of using $RANDOM and limiting its range

flowchart TD
    A[Start] --> B{Access $RANDOM}
    B --> C[Get 0-32767]
    C --> D{Need specific range?}
    D -- Yes --> E[Apply Modulo and Offset]
    E --> F[Result: In-range Integer]
    D -- No --> F
    F --> G[End]

Flowchart for generating random numbers using $RANDOM

Generating Cryptographically Secure Random Numbers with /dev/urandom

For applications requiring higher security, such as generating passwords, encryption keys, or session tokens, /dev/urandom is the preferred source of randomness. This special file provides an interface to the kernel's cryptographically secure pseudo-random number generator (CSPRNG). It will never block, making it suitable for scripts that need to generate random data quickly without waiting for sufficient entropy.

# Generate 16 random bytes (128 bits) in hexadecimal format
head /dev/urandom | tr -dc A-Za-z0-9_ | head -c 16 ; echo

# Generate a random integer between 1 and 100 using /dev/urandom
# This method is more complex but cryptographically stronger
RAND_BYTE=$(head /dev/urandom | od -An -N1 -i)
RAND_1_100=$(( RAND_BYTE % 100 + 1 ))
echo "Secure random number (1-100): $RAND_1_100"

# Generate a random password of 12 characters
PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9_@#$%^&*-+= | head -c 12 ; echo)
echo "Generated password: $PASSWORD"

Examples using /dev/urandom for secure random data

Using shuf for Random Permutations and Selections

The shuf command (from GNU coreutils) is excellent for shuffling lines from a file or generating random permutations of a sequence of numbers. It's particularly useful when you need to select a random item from a list or generate a unique sequence of numbers within a range.

# Select a random line from a file
cat /etc/passwd | shuf -n 1

# Generate 5 unique random numbers between 1 and 100
seq 1 100 | shuf -n 5

# Pick a random fruit from a list
FRUITS=("Apple" "Banana" "Cherry" "Date" "Elderberry")
RANDOM_FRUIT=$(printf "%s\n" "${FRUITS[@]}" | shuf -n 1)
echo "Random fruit: $RANDOM_FRUIT"

Examples of using shuf for random selections and permutations

Choosing the right method for generating random numbers in Bash depends entirely on your specific needs. For simple, non-critical tasks, $RANDOM is quick and easy. For security-sensitive operations, /dev/urandom is the go-to. And for shuffling or selecting unique items, shuf offers a convenient solution. Understanding these options allows you to write robust and appropriate Bash scripts.