Skip to content

Latest commit

 

History

History
49 lines (33 loc) · 1.83 KB

3.md

File metadata and controls

49 lines (33 loc) · 1.83 KB

Chapter 3: The Operator Odyssey 🤖

3 - Getting random numbers

Random Function in Linux

What is Random Function in Linux?

The random function in Linux is a built-in feature that allows users to generate random numbers. It is often used in shell scripts and command-line utilities to introduce randomness into various tasks, such as generating passwords, simulating dice rolls, or selecting random elements from a list.

Examples of Using Random Function in Linux

1. Getting a Random Number

To generate a random number in Linux, you can use the $RANDOM variable, which returns a random integer between 0 and 32767 each time it is referenced. Here's an example:

#!/bin/bash

# Generate a random number
echo "Random number: $RANDOM"

2. Getting a Random Number Within a Range

To generate a random number within a specific range, you can use the modulo operator (%). For example, to generate a random number between 1 and 100:

#!/bin/bash

# Generate a random number within a range
echo "Random number between 1 and 100: $((RANDOM % 100 + 1))"

3. Getting a Random Number Between Two Given Numbers

To generate a random number between two given numbers, you can use the formula ((RANDOM % (max - min + 1)) + min). For example, to generate a random number between 10 and 20:

#!/bin/bash

# Generate a random number between two given numbers
min=10
max=20
echo "Random number between $min and $max: $((RANDOM % ($max - $min + 1) + $min))"

Conclusion

These examples demonstrate how to use the random function in Linux to generate random numbers for various purposes. Incorporating randomness into scripts can add versatility and unpredictability to your applications.

⬅️Previous-----------Next ➡️

Table of contents 🚀