How to Run Multiple Bash Scripts Simultaneously in Terminal

bashgnome-terminalshell-scriptterminalUbuntu

I need to run several Bash scripts (the same script with different variables to be precise) at the same time. To keep the number of tabs under control, I wish to group them in a single terminal tab.

The scripts regularly output, which I check for any problem.

If I send them to the background as

./script.sh 1 &
./script.sh 2 &
./script.sh 3 &
./script.sh 4

I will lose control over them. For example, I terminate the script by Ctrl+C. With the above code, I should find the pid for each process to kill them.

Note that the above code is the content of my main script (say ./all_scripts.sh) rather than commands to be typed in the terminal.

Is there a way to run the script in the same terminal while treating them as a single outputting script?

Best Answer

You don't lose control over them. You're sending them (other than the last one) to the background.

If you run the command chain you specify, the invocation ./script.sh 4 will be in the foreground, and the other scripts will be running in the background. Input will be sent to the foreground script. To suspend the foreground script, press CtrlZ. To send the suspended script to the background to continue running, use the bg command.

To see the scripts (or more correctly, jobs) you have and the states they're in, use jobs.

To bring a specific job to the fore, use fg and its number (as reported by the aforementioned jobs) with a % prefix, e. g. fg %2. To terminate a specific job, you can either bring it to the foreground with fg and terminate it sanely, or you can kill it, e. g. kill -TERM %2.

Related Question