我有一个Shell脚本,可以在不打开新终端的情况下并行执行两个命令
我的脚本
#!/bin/sh
sudo command1 &
sudo command2
我需要一个Shell脚本,该脚本应在执行Shell脚本的终端中按cntl + c时终止
答案 0 :(得分:0)
创建一个函数,以使用trap
在退出时执行。注册分叉进程的进程ID,并在退出函数中终止该PID。
FORKED_PID=
# this function will be executed when the script is terminated for any reason
function finish() {
# get the process id of the process with parent process id $FORKED_PID, and kill it
sudo kill -9 `ps --ppid $FORKED_PID -o pid=`
}
# bind this function to the EXIT signal
trap finish EXIT
# run command1 with sudo
sudo command1 &
# get the process id from the previous command and put it in $FORKED_PID
FORKED_PID=$!
# run command2 with sudo
sudo command2