Random Number Generation Methods
Linux provides multiple approaches for generating pseudo-random numbers suitable for various applications including verification codes, SSH port forwarding, and shell scripting.
Using the shuf Commend
The shuf utility generates random permutations and is available by default on many distributions including Ubuntu 20.04:
Generate a single random integer within a specific range:
shuf -i 30000-40000 -n 1
Select a random line from a text file:
shuf sample.txt
Randomly choose from command-line argumeents:
shuf -e "option1" "option2" "option3"
Extract 5 random lines from input:
shuf -n 5 data.txt
Write randomized output to a new file:
shuf source.txt -o randomized.txt
Key parameters include:
-e, --echo: Treat arguments as input lines-i, --input-range=LOW-HIGH: Specify numeric range-n, --head-count=NUM: Limit output lines-r, --repeat: Allow repeated selections-z, --zero-terminated: Use null character as separator-o, --output=FILE: Redirect output to file
AWK-Based Generation
Generate cryptographically suitable random values using AWK:
awk -v lower=30000 -v upper=40000 'BEGIN{srand(); print int(lower+rand()*(upper-lower+1))}'
Utilziing /dev/urandom Device
Extract random data from system entropy source:
port_num=$(od -An -N2 -i /dev/urandom | awk -v low=30000 -v high=40000 '{ print ($1 % (high - low + 1)) + low }')
Unlike /dev/random, which blocks when entropy is depleted, /dev/urandom continues generating output making it suitable for non-cryptographic purposes requiring continuous random number streams.
Shell Built-in Variable Approach
Access the $RANDOM environment variable for basic random number generation:
echo $RANDOM
This produces values between 0 and 32767. To generate single-digit numbers:
echo $(($RANDOM%10))
For two-digit output:
echo ${RANDOM:0:2}
To create numbers within custom ranges like 6-87:
echo $(($RANDOM%82+6))
All these methods produce pseudo-random sequences. For cryptographic applications requiring true randomness, physical processes such as radioactive decay or thermal noise should be employed instead of algorithmic generators.