user142019
user142019

Reputation:

Select a random item from an array in Bash

I'm creating a bot in Shell Script:

# Array with expressions
expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")

# Seed random generator
RANDOM=$$$(date +%s)

# Loop loop loop loop loop loop ...
while [ 1 ]
do
    # Get random expression...
    selectedexpression=${expressions[$RANDOM % ${#RANDOM[*]}]}
    
    # Write to Shell
    echo $selectedexpression
    
    
    # Wait an half hour
    sleep 1 # It's one second for debugging, dear SOers
done

I want that it prints a random item from the expressions every second. I tried this but it does not work. It only prints the first one (Ploink Poink) every time. Can anyone help me out?

Upvotes: 95

Views: 75342

Answers (6)

gae123
gae123

Reputation: 9457

For use cases where a bit of python is OK so it becomes a one liner and readable, here is another take:

echo $(python3 -c "import random;print(random.choice(['a','b','c']))")

Upvotes: -1

Netwons
Netwons

Reputation: 1648

for random

1.

rand=("q" "w") 
r=$(shuf -i 0-${#rand[@]} -n 1)
echo ${rand[$r]}
echo `$((1 + $RAND % 5))` // **for number between 1..5**

Upvotes: 2

Jacob Mattison
Jacob Mattison

Reputation: 51062

Change the line where you define selectedexpression to

selectedexpression=${expressions[ $RANDOM % ${#expressions[@]} ]}

You want your index into expression to be a random number from 0 to the length of the expression array. This will do that.

Upvotes: 138

presto8
presto8

Reputation: 517

Solution using shuf:

expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(printf "%s\n" "${expressions[@]}" | shuf -n1)
echo $selectedexpression

Or probably better:

select_random() {
    printf "%s\0" "$@" | shuf -z -n1 | tr -d '\0'
}

expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(select_random "${expressions[@]}")
echo "$selectedexpression"

Upvotes: 6

noobninja
noobninja

Reputation: 910

arr[0]="Ploink Poink"
arr[1]="I Need Oil"
arr[2]="Some Bytes are Missing!"
arr[3]="Poink Poink"
arr[4]="Piiiip Beeeep!!"
arr[5]="Hello"
arr[6]="Whoops! I'm out of memmory!"
rand=$[$RANDOM % ${#arr[@]}]
echo $(date)
echo ${arr[$rand]}

Upvotes: 30

Powers
Powers

Reputation: 19328

Here's another solution that may be a bit more random than Jacob Mattison's solution (hard to say from the jot manpages):

declare -a expressions=('Ploink' 'I Need Oil' 'Some Bytes are Missing' 'Poink Poink' 'Piiiip Beeeep' 'Hello' 'Whoops I am out of memory')
index=$( jot -r 1  0 $((${#expressions[@]} - 1)) )
selected_expression=${expressions[index]}

Upvotes: 5

Related Questions