random


Generate Random Password

date +%s | sha256sum | base64 | head -c 32 ; echo
date +%s : will print the system date and time in seconds since 1970-01-01 00:00:00 UTC

sha256sum :  will compute  the SHA256 message digest of the time in seconds we produced before

base64 : will encode the previous data and print them to standard output

head -c 32 : will print the first 32 characters of the previous data

; echo : is used to create a new line at the end of the results


Bash: Get random number that belongs in a range 1

In case you need to create a random number that is between a certain range, you can do it in a very easy way in bash.

Bash has the $RANDOM internal function that returns a different (pseudo) random integer at each invocation. The nominal range of the results is 0 – 32767 (it is the range of a signed 16-bit integer).

We use the result of $RANDOM to create our number using the following script:

FLOOR=10;
CEILING=100;
RANGE=$(($CEILING-$FLOOR+1));
echo "You will generate a random number between $FLOOR and $CEILING (both inclusive). There are $RANGE possible numbers!"
RESULT=$RANDOM;
echo "We just generated the random number $RESULT, which might not be in the range we want";
let "RESULT %= $RANGE";
RESULT=$(($RESULT+$FLOOR));

echo "Congratulations! You just generated a random number ($RESULT) the is in between $FLOOR and $CEILING (inclusive)";

We use basic math operations on the variables to create the random number that is in the range we like without need-less loops.

What we do is:

  1. We compute the length of the range of valid numbers (ceiling-floor)
    Here we added the +1 because we want the ceiling to be included in the result set.
  2. We generate a random number that is between 0 and the length of range using modulo to limit the results.
  3. We add to the result the value of the floor and this create our final result which is a number equal or greater to the floor and equal or smaller to the ceiling