I want to run multiple commands (processes) on a single shell. All of them have own continuous output and don't stop. Running them in the background breaks Ctrl–C. I would like to run them as a single process (subshell, maybe?) to be able to stop all of them with Ctrl–C.
To be specific, I want to run unit tests with mocha
(watch mode), run server and run some file preprocessing (watch mode) and see output of each in one terminal window. Basically I want to avoid using some task runner.
I can realize it by running processes in the background (&
), but then I have to put them into the foreground to stop them. I would like to have a process to wrap them and when I stop the process it stops its 'children'.
Best Answer
To run commands concurrently you can use the
&
command separator.This will start
command1
, then runs it in the background. The same withcommand2
. Then it startscommand3
normally.The output of all commands will be garbled together, but if that is not a problem for you, that would be the solution.
If you want to have a separate look at the output later, you can pipe the output of each command into
tee
, which lets you specify a file to mirror the output to.The output will probably be very messy. To counter that, you could give the output of every command a prefix using
sed
.So if we put all of that together we get:
This is a highly idealized version of what you are probably going to see. But its the best I can think of right now.
If you want to stop all of them at once, you can use the build in
trap
.This will execute
command1
andcommand2
in the background andcommand3
in the foreground, which lets you kill it with Ctrl+C.When you kill the last process with Ctrl+C the
kill %1; kill %2
commands are executed, because we connected their execution with the reception of an INTerupt SIGnal, the thing sent by pressing Ctrl+C.They respectively kill the 1st and 2nd background process (your
command1
andcommand2
). Don't forget to remove the trap, after you're finished with your commands usingtrap - SIGINT
.Complete monster of a command:
You could, of course, have a look at screen. It lets you split your console into as many separate consoles as you want. So you can monitor all commands separately, but at the same time.