How do you generate random numbers in a shell script?
Generating random numbers in Shell scripts can be done in multiple ways. Here, I will cover two commonly used methods: using the variable and using the file.Method 1: Using the VariableShell environments include a built-in variable , which returns a random integer between 0 and 32767 each time it is referenced. If you need a random number within a specific range, such as from 1 to 100, you can use the following expression:Here, is the modulo operator, and the result of will be a random integer between 1 and 100.Example:Suppose we need to randomly select a user for a specific operation in the script. We can write the script as follows:In this script, we first define a user array, then use to obtain a random index, and finally select a user from the array.Method 2: Using the FileIf stronger randomness is required, you can use the special device file , which provides an interface to obtain high-quality random numbers. Use the (octal dump) command to read random data from and format the output.This command reads 4 bytes of data and outputs it as an unsigned integer. The option suppresses address display, specifies reading 4 bytes, and indicates interpreting the input as an unsigned 4-byte integer.Example:Suppose we need to generate a random 16-bit port number (between 1024 and 65535) in the script. We can use the following script:This script reads two bytes of data from , ensuring the generated number is at least 1024. If the original number is less than 1024, it adjusts it to be above 1024.In summary, the variable is suitable for basic random number needs, while is appropriate for scenarios requiring higher randomness. When writing scripts, choose the appropriate method based on your specific requirements.