- 9.6. $RANDOM: генерация псевдослучайных целых чисел
- Сгенерировать случайное число в bash
- Использование случайного генератора:
- Генерация случайных чисел с использованием переменной $RANDOM:
- A. Генерация случайных чисел с терминала
- Б. Генерация случайных чисел с помощью скрипта
- Генерация случайных чисел с помощью команды shuf:
- A. Генерация случайных чисел с терминала
- Б. Генерация случайных чисел с помощью скрипта
- Генерация случайных чисел с помощью /dev/urandom:
- Заключение:
- Bash Shell Generate Random Numbers
- Using /dev/urandom or /dev/random
- Recommended readings:
9.6. $RANDOM: генерация псевдослучайных целых чисел
$RANDOM — внутренняя функция Bash (не константа), которая возвращает псевдослучайные целые числа в диапазоне 0 — 32767. Функция $RANDOM не должна использоваться для генераци ключей шифрования.
Пример 9-23. Генерация случайных чисел
Пример 9-24. Выбор случайной карты из колоды
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Thanks for the tips. Two mistake though:
– ‘echo $(( r %= 200 ))’ should be ‘echo $(( n %= 200 ))’
– ‘echo $((RANDOM%200+100))’ return a number between 100 and 300, not 100 and 200 as commented above.
The example involving 200 is not a uniform distribution. The mapping function used is f(x) = x module 200. This input, x, is a uniform distribution. The output f(x) is not because the the size of the domain is a power of 2 and the size of the range is 200. if f(x) were random, the size of the domain would be a multiple of the size of the range. A power of 2 is never a multiple of 200. The following would be random: while (set I to $RANDOM) Nice topic. echo $(( n %= 200 )) Will return an integer strictly less than 200. I think that If you want to include 200, you could use: echo $(( n %= 200 + 1)) But then, [n] will never be zero, it will belong to [1;200] Then if you want a random integer belonging to [0;200], echo $(( n %= 201)) Like the man page excerpt above says, you can initialize the sequence by assigning an arbitrary number to RANDOM before using it. If you don’t want the same ‘random’ sequence each time you run the script, you should seed RANDOM by assigning an arbitrary number before using it. The process ID works well: OpenSSL can also be used as a source of random numbers, and is a good idea if the numbers are going to be used for cryptographic key generation or nonces. The generator used by OpenSSL uses a FIPS 140 approved algorithm and has been widely tested and reviewed. OpenSSL on Unix systems will leverage available entropy from the OS RNG as part of it’s seed/start process. Here are some sample commands – quoted from the “OpenSSL Command-line HOWTO”: # write 128 random bytes of base64-encoded data to stdout # write 1024 bytes of binary random data to a file Cheers, Erik Is there any way to do this with a custom random seed? vivek, # display random number between 100 and 200. This will display random number between 100 and 300 (not 200) If you want to display random number between 100 and 200, use: echo $((RANDOM%100+100)) Would you modify yor code above? actually it’s between 100 and 299. #Bug in ‘display random number between 100 and 200.’ #For determine the random number between x and y is: Works good: example: maximal=10 minimal=5 try it 😉 Or if you want numbers between 5 – 10, you can do this: You may be overwhelmed or overloaded, 1) As Dago said: 2) Typo 3) Misunderstanding KUTGW, I really appreciate your site – as usual, great work. Hi Nice and instructive post! May be a good way for seeding randomness would be using time: in a simplest exposure: Nanosecond semi-random number generator Can also be used as $RANDOM shuffler: $ RANDOM=$(date +’%N’) Random entropy pool init with subsequent selection of some text to echo. ‘+’ should never hit (%3 + 1 == 1 to 3). Output will be 1,2 or 3. RANDOM=`date +%s%N | cut -b14-19`; I find ‘shuf’ to be a good solution. You can specify the range and how many numbers you want back, as well as a random source to make it repeatable when testing. RANDOM=$(shuf -i 1-1000 -n 1) although it’s probably as good as using ‘od’. Using $RANDOM works, but technically won’t give you a very even distribution (as it’s between 0 and 32767 before you % 100 it or whatever). Источник
Precision:
you may use:
openssl rand -base64 128
openssl rand -out random-data.bin 1024
ArtofInfoSec.com
There is a bug here:
echo $((RANDOM%200+100))
echo $((RANDOM%200+100))
echo $((x + RANDOM%(y-x+1)))
echo $(( RANDOM% ($maximal – $minimal) + $minimal ))
echo $(( RANDOM% 5 + 5 ))
5 – minimum, maximum is +5 bigger
but you will also find that this page does not meet your quality standard.
#To get random integer number between x and y, x and y beeing included as in [x;y] notation, use:
echo $((x + RANDOM%(y-x+1)))
There is still a typo here: echo $(( r %= 200 ))
Should be: echo $(( n %= 200 ))
Why do you use “%=” where “%” will be appropriate ?
That is: echo $(( n %= 200 ))
Should be: echo $(( n % 200 ))
that was useful, didn’t know there was more than one method to generate random number.
I was looking for a way to seed the $RANDOM-ness in bash, and I found this can be done by setting the $RANDOM variable:
$ RANDOM=1
$ echo $RANDOM
16807
$ echo $RANDOM
15089
$ RANDOM=1
$ echo $RANDOM
16807
$ echo $RANDOM
15089
$ RANDOM=$(date +%s)
$((RANDOM%offsetFromLowest+Lowest))
$ echo $RANDOM
13967
$ RANDOM=$(date +’%N’)
$ echo $RANDOM
27211
case $[$RANDOM % 3 + 1] in 1) echo ‘1’;; 2) echo ‘2’;; 3) echo ‘3’;; *) echo ‘+’;; esac