Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run parallel multiple commands at once in the same terminal

Tags:

linux

bash

I want to run a few commands, each of which doesn't quit until Ctrl-C is pressed. Is there something I can run to run all of them at once, and Ctrl-C will quit them all? They can share the terminal output.

Specifically, I have the compass compiler, coffeescript compiler, and a custom command that watches for file changes all running watching for file changes. I don't want to load up a terminal for each command.

like image 914
Oliver Zheng Avatar asked Jun 06 '12 07:06

Oliver Zheng


People also ask

How do I run multiple commands in parallel Linux?

Method #1: Using the Semicolon Operator Here, you can have as many commands as you want to run in parallel separated by semicolons.


2 Answers

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.

#!/bin/bash  for cmd in "$@"; do {   echo "Process \"$cmd\" started";   $cmd & pid=$!   PID_LIST+=" $pid"; } done  trap "kill $PID_LIST" SIGINT  echo "Parallel processes have started";  wait $PID_LIST  echo echo "All processes have completed"; 

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3" 

Example:

parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4" 

Start 4 parallel sleep and waits until "sleep 4" finishes.

like image 63
Alessandro Pezzato Avatar answered Sep 21 '22 08:09

Alessandro Pezzato


Based on comment of @alessandro-pezzato. Run multiples commands by using & between the commands.

Example:

$ sleep 3 & sleep 5 & sleep 2 & 

It's will execute the commands in background.

like image 45
nsantana Avatar answered Sep 23 '22 08:09

nsantana