Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick and print one of three strings at random in Bash script

Tags:

bash

shell

random

How can print a value, either 1, 2 or 3 (at random). My best guess failed:

#!/bin/bash

1 = "2 million"
2 = "1 million"
3 = "3 million"

print randomint(1,2,3)
like image 924
Switchkick Avatar asked Mar 04 '11 05:03

Switchkick


People also ask

How do I generate a random name in bash?

Method 1: md5 Hash The very first method we can use to generate a random string in bash is md5 checksums. Bash has the $RANDOM variable, which produces a random number. We can pipe this value to md5sum to get a random string. The $RANDOM variable is always random.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

To generate random numbers with bash use the $RANDOM internal Bash function:

arr[0]="2 million"
arr[1]="1 million"
arr[2]="3 million"

rand=$[ $RANDOM % 3 ]
echo ${arr[$rand]}

From bash manual for RANDOM:

Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset,it loses its special properties, even if it is subsequently reset.

like image 199
codaddict Avatar answered Nov 03 '22 21:11

codaddict