Simple method to shuffle the elements of an array in BASH shell?

The accepted answer doesn’t match the headline question too well, though the details in the question are a bit ambiguous. The question asks about how to shuffle elements of an array in BASH, and kurumi’s answer shows a way to manipulate the contents of a string.

kurumi nonetheless makes good use of the ‘shuf’ command, while siegeX shows how to work with an array.

Putting the two together yields an actual “simple method to shuffle the elements of an array in BASH shell”:

$ myarray=( 'a;' 'b;' 'c;' 'd;' 'e;' 'f;' )
$ myarray=( $(shuf -e "${myarray[@]}") )
$ printf "%s" "${myarray[@]}"
d;b;e;a;c;f;

Leave a Comment