It is very easy to generate random numbers in Unix. Easiest way is to use the variable $RANDOM.

Every time if you echo $RANDOM, you would get a new number between 0 and 32767.

## Generate Random Number using $RANDOM in Unix

Let us try echo $RANDOM couple of times.

`echo $RANDOM`

`10557`

`echo $RANDOM`

`8631`

As we see above, every time we echo $RANDOM, a new number is generated.

But how about generating the same random number as it is required in many applications such as machine learning. Check out post Generate Random Numbers in Python.

Ok, to generate same random number, we need to provide the seed. '$$' variable in bash contains the pid. Therefore we can provide '$$' (pid) as seed number to generate same RANDOM number.

Let us print the value of pid first.

`echo $$`

`253689`

Ok let us initialize the RANDOM variable to our seed value as shown below.

`RANDOM=$$`

Now let us print the value of $RANDOM

`echo $RANDOM`

`11632`

Let us run the above two commands again to make sure we get the same random number with our same seed value.

```
RANDOM=$$
echo $RANDOM
```

`11632`

There you go, we got the same RANDOM number again.

We can also mix $RANDOM with other bash commands such as 'seq' to generate multiple numbers.

Let us generate the 3 random numbers using 'seq 3' command.

```
for i in `seq 3`;do
echo $RANDOM
done
```

```
21698
14809
1884
```

We can also limit the upper bound on Random number which is generated.

Let us say, we want to generate the random number less than 100.

`echo $(($RANDOM%100))`

`91`

How about generating 3 random numbers less than 3.

```
for i in `seq 3`;do
echo $(($RANDOM%100))
done
```

```
7
42
70
```

## Generate Random Numbers using shuf in Unix

shuf is a great bash Utility to generate random numbers in Unix.

shuf syntax is...

`shuf -i MIN-MAX -n COUNT`

Let us generate 3 random numbers using shuf between 10 and 100.

`shuf -i 10-100 -n 3`

```
13
86
59
```

### Generate Random Decimal Numbers using Awk in Unix

Below command will generate 5 random decimal numbers with precision up to 3 decimal places. Note rand() will generate a random number between 0 and 1. srand(seed) sets the seed for generating random numbers.

`awk -v n=5 -v seed="$RANDOM" 'BEGIN { srand(seed); for (i=0; i<n; ++i) printf("%.3f\n", rand()) }'`

```
0.585
0.598
0.650
0.476
0.630
```