How to Generate Random Numbers in Linux Shell Scripting with an index
There could be situations wherein you need to create random number or a random file name or a random password. Lets do it through a shell script.
To generate a random number in a UNIX or Linux shell, the shell called a shell variable named RANDOM. Each time this variable is called, a random number between 0 and 32767 is generated.
The RANDOM variable should be initialized to an initial value (ike the process ID of the current shell, which is maintained by the variable $$.
Example 1:
Lets check how we generate 10 random numbers.
Script:
generate 10 random numbers |
Example 2: Let Generate as many as random numbers you want
We will generate as many as random numbers we want by giving a positional argument while executing the script.
Script:
Example 3: Let Generate as many as random numbers you want with an Index
We will generate as many as random numbers we want by giving a positional argument while executing the script. It will add an index to it.
Script:
Example 4: Let Generate as many as random numbers you want with an Index and with a default value for Positional argument.
We will generate as many as random numbers we want by giving a positional argument while executing the script. It will add an index to it. If we do not provide an positional argument to the script it'll take 10 as default value.
Script:
Positional Argument with default Value |
Output: Make the script executable and then run the script.
Example 5: Let Generate as many as random numbers you want with an Index and with a default value for Positional argument. Send the Generated value to a file.
We will generate as many as random numbers we want by giving a positional argument while executing the script. It will add an index to it. If we do not provide an positional argument to the script it'll take 10 as default value. As a final nail in the coffin it'll send the output to a file.
Script:
Positional Argument with default Value. Send Output to a file |
Output: Make the script executable and then run the script.
No comments