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

后端 未结 3 1161
眼角桃花
眼角桃花 2020-11-29 09:37

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.

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 10:14

    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;
    

提交回复
热议问题