1

I run several bash scripts in separate terminal windows (tabs). I want to mix them to run in the same window and provide mix outputs. I just need to initiate all scripts independently in the same window.

The common solution is to use & as

./script1 &
./script2 &
./script3

BUT I don't want to send the scripts to work in the background since I do not have control over them in the terminal. For example, I cannot terminate this script by Ctrl+C, as the background processes will not be killed by Ctrl+C.

  • 3
    I think you need to read LESS='+/^JOB CONTROL' man bash. In particular, you can run the jobs builtin to see a list of current jobs, and can kill them using jobspecs such as kill %2 and so forth. – Wildcard Mar 1 at 20:39
  • 2
    Would something like GNU parallel be useful? – kemotep Mar 1 at 20:42
  • Read up on the pkill man page: that will make it easier to send an INT signal to the right process. – glenn jackman Mar 1 at 20:48
  • If you run all three and press ctrl+c which one do you want to end? – Jesse_b Mar 1 at 21:15
  • @Jesse_b I want to end all, like it is a single script. – Googlebot Mar 1 at 21:46
5

You can run your scripts in tmux or screen in almost any number of background processes. Those processes can be accessed in any time you want.

See tmux or GNU screen

3

You could write a wrapper script around them that sends them all to the background and then traps ctrl+c:

#!/bin/bash

trap ctrl_c INT

scripts=( ./script1.sh ./script2.sh ./script3.sh )

ctrl_c () {
    printf 'Found [%i] PIDs running\n' "${#pids[@]}"
    for pid in "${pids[@]}"; do
        printf 'Killing PID: %i\n' "$pid"
        kill "$pid"
    done
}

for script in "${scripts[@]}"; do
    "$script" &
    pids+=($!)
done

for pid in "${pids[@]}"; do
    wait "$pid"
done

So if you press ctrl+c it will kill all the pids that have been previously captured:

$ cat ./script{1..3}.sh
#!/bin/bash

sleep 30; echo foo
#!/bin/bash

sleep 30; echo bar
#!/bin/bash

sleep 30; echo baz

$ ./script4.sh
^CFound [3] PIDs running
Killing PID: 48971
Killing PID: 48972
Killing PID: 48973
./script4.sh: line 21: 48971 Terminated: 15          "$script"
./script4.sh: line 21: 48972 Terminated: 15          "$script"
./script4.sh: line 21: 48973 Terminated: 15          "$script"
0

Try:

parallel -j0 --line-buffer ::: ./script1 ./script2 ./script3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.