0

I don't have a question, just an update for anyone who needs this information which was very hard for me to find.

Using the $RANDOM command in a bash script to call a string from an array. I had a hard time finding the syntax to this. The example is below.

#!/bin/bash

# (Will not run with older #!/bin/sh)

arrayList=(word1 word2 word3 word4)

echo "The output from arrayList is: ${arrayList[$RANDOM % ${#arrayList[@]}]}"

And the output will be one of the words in the parentheses:

The output from arrayList is: word3

(Every time you run this script, one of the words will be randomly chosen).

I tried finding the similar syntax for shuf, but I couldn't find the syntax. I got the syntax for it to choose a word randomly, but I couldn't get it to work within an echo command like $RANDOM above.

Thank you.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
fsuit
  • 1
  • 1
    In the future, if you want to document such a finding, you should post is as a question/answer pair - this is totally fine, as long as the question is a good question and not overly specific, or too broad, or opinion-based etc.; the same criteria as for any question. – Benjamin W. Mar 03 '20 at 05:04
  • Oh ok, I didn't see a question/answer pair option when I posted it. But thank you. I can do that next time. – fsuit Mar 04 '20 at 16:24

0 Answers0