Home > front end >  Shuffle random list of COMMANDS in BASH?
Shuffle random list of COMMANDS in BASH?

Time:11-30

I have a list of commands in a text file named commands.txt:

cat file1.txt | sort > file1.txt
cat file2.txt | sort > file2.txt
etc

What I want to do is randomize that file and then execute each line in random order. I have tried the following in a cmd.sh shell script:

while read -r -a array
do
    "${array[@]}"
done < <(shuf commands.txt)

And all Bash does is yell at me that it's a syntax error with an unexpected token <

This is on MacOS 10.14 with bash 3.2.57 and zsh 5.8.

Does anyone know how to do this?

CodePudding user response:

You can pipe the shuffled commands to bash without any processing:

shuf commands.txt | bash

CodePudding user response:

Pipes (|) and redirection (>) will not work in a variable. You can use eval "${array[@]}", or bash -c "${array[*]}" instead.

Also if you do cat file > file, file will be truncated (emptied) before cat is executed. So you'll just have empty files. You can do sort file1.txt > tmp && mv tmp file1.txt

  • Related