How can I run multiple Bash scripts simultaneously in a terminal window?
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
.
After testing different methods and programs, I found that the pragmatic solution is GNU Parallel. I post this answer as it may help others.
GNU Parallel
has not been built for this task, but perfectly serves the purpose.
If running the scripts as
parallel -u ::: './script.sh 1' './script.sh 2' #(and so forth)
All scripts will be run in parallel.
The -u
(--ungroup
) flag sends the script outputs into stdout
while executing the scripts.
Ctrl+C kills the parallel
job, and subsequently all running scripts.
You can use tmux
for this.
It is a terminal multiplexer meaning that it splits one tab into multiple windows.
- Start it with the command
tmux
. - Use
Contr
+B followed by"
or%
in order to split a pane into two panes. - Start processes in the foreground.
- Switch between the processes uding
Contr
+B
followed by arrow keys.
Now you have normal control over multiple processes in one tab of your terminal.
If you want to focus (or unfocus) a specific pane, use Contr
+B
followed by Z
.
If you need to scroll use Contr
+B
followed by Q
and scroll using arrow keys(or activate mouse mode).
You can find a cheatsheet here.
It is also possible to automate that process.