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

Dave picture Dave · Apr 4, 2011 · Viewed 17.2k times · Source

I can do this in PHP but am trying to work within the BASH shell. I need to take an array and then randomly shuffle the contents and dump that to somefile.txt.

So given array Heresmyarray, of elements a;b;c;d;e;f; it would produce an output file, output.txt, which would contain elements f;c;b;a;e;d;

The elements need to retain the semicolon delimiter. I've seen a number of bash shell array operations but nothing that seems even close to this simple concept. Thanks for any help or suggestions!

Answer

David McKinley picture David McKinley · Feb 12, 2017

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;