1

I'm new to shell script and am having an issue with the shuf function. This is my code

declare -a myarray=( 'A' 'B' 'C' 'D' 'E' 'F' )
myarray = $(shuf -e "${myarray[@]}")
echo "$myarray"

I make an array containing the six characters. I then shuffle them randomly, and print them out. My issue is that if I were to add another line, for example

echo ${myarray[2]}

This doesn't actually print the randomly sorted character in the 3rd position. Instead, it will always print 'C'. How can I actually save the sorted array? Do I need to make another array?

Thank you very much

E. Cheng
  • 23
  • 1
  • 6

1 Answers1

1

Arrays in bash are defined with (). Bash is not statically typed, so setting myarray equal to some output of characters will do just that, making it a string you can echo with echo $myarray to see the full output.

You need to wrap your output in parens to make it clear to bash that your new myarray should also be an array:

myarray=($(shuf -e "${myarray[@]}"))
jeremysprofile
  • 10,028
  • 4
  • 33
  • 53