How to run several commands on a Linux system in parallel mode?

Problem

You would like to run several commands at the same time, but each of them should be run in a separate thread. The following script will allow you to do this.

#!/bin/bash

for cmd in "$@"; do {
  echo "--> Running \"$cmd\" command!";
  $cmd & pid=$!
  RUN_PID_LIST+=" $pid";
} done

trap "kill $RUN_PID_LIST" SIGINT
echo "--> Commands were run...";
wait $RUN_PID_LIST
echo "--> All your processes have been completed!";

 

Then run the command.

./run_parallel.sh "echo 1" "sleep 2" "echo 2" "sleep 2"

You will get the result as below:

./run_parallel.sh "echo 1" "sleep 2" "echo 2" "sleep 2"
--> Running "echo 1" command!
--> Running "sleep 2" command!
1
--> Running "echo 2" command!
--> Running "sleep 2" command!
2
--> Commands were run...
--> All your processes have been completed!

 

If you enjoyed this post please leave the comment below or share this post on your Facebook, Twitter, LinkedIn or another social media webpage.
Thanks in advanced!

Please follow and like us:
error

Leave a Reply

Close Menu
Social media & sharing icons powered by UltimatelySocial
error

Enjoy this blog? Please spread the word :)