我在单独的终端窗口(选项卡)中运行多个 bash 脚本。我想将它们混合在同一窗口中运行并提供混合输出。我只需要在同一个窗口中独立启动所有脚本。
常见的解决方案是使用&
as
./script1 &
./script2 &
./script3
但我不想发送脚本在后台工作,因为我无法在终端中控制它们。例如,我无法通过 终止此脚本Ctrl+C
,因为后台进程不会被 终止Ctrl+C
。
答案1
答案2
您可以在它们周围编写一个包装器脚本,将它们全部发送到后台,然后捕获 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
因此,如果您按 ctrl+c ,它将杀死之前捕获的所有 pid:
$ 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"
答案3
尝试:
parallel -j0 --line-buffer ::: ./script1 ./script2 ./script3