Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 1003  / 3 Years ago, wed, november 3, 2021, 5:18:21

The question is related to bash, Linux like Ubuntu, /dev/random and /dev/urandom .


How to generate a random number in a range which can be positive or negative, by /dev/urandom on bash ?


Known are:



Follow are a sample for a not searched solution to do it in a range on bash, by not searched function "RANDOM" and only in a positive range.


min=1
max=1000
rnd_count=$(( RANDOM % ( max - min + 1 ) + min ))
echo $rnd_count

A partly solution is to generate a random number by bash random or urandom on positive range works on follow way, how to do this on positive and negative range too, is unknown fo me. And its not pure bash. A pure bash solution are wanted.


echo "$(od -An -N4 -tu4 /dev/urandom) % 15 + 1" | bc


More From » bash

 Answers
3

The simplest, cleanest way I can think of is what you already have in your question:


min=-100; max=1; rnd_count=$(( RANDOM % ( $max - $min + 1 ) + $min )); echo $rnd_count

You can easily convert that into a function:


getRand(){
min="${1:-1}" ## min is the first parameter, or 1 if no parameter is given
max="${2:-100}" ## max is the second parameter, or 100 if no parameter is given
rnd_count=$((RANDOM % ( $max - $min + 1 ) + $min )); ## get a random value using /dev/urandom
echo "$rnd_count"
}

If you either paste those lines into your terminal or add them to your ~/.bashrc file and open a new terminal, you can now do:


$ getRand -5 5
-3

That gives a random number between -5 and 5.


[#1900] Wednesday, November 3, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravturtl

Total Points: 335
Total Questions: 132
Total Answers: 110

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;