我编写了一个 bash 脚本来自动执行一个很长的过程。效果很好。
但是,如果用户应该 control-c 或由于 ssh 断开连接而重新运行,我发现如果我执行以下命令,则先前执行的剩余部分仍在运行: ps -ef|grep myprogram。
我相信问题出在这段代码中,我在其中设置了每个步骤的背景,以便可以向用户显示旋转的进度条:
<snippet begin>
function progress {
SPIN='-\|/'
# Run the base 64 code in the background
echo $THECOMMAND | base64 -d|bash &
pid=$! # Process Id of the previous running command
i=0
while kill -0 $pid 2>/dev/null
do
i=$(( (i+1) %4 ))
# Print the spinning icon so the user knows the command is running
printf "\r$COMMAND:${SPIN:$i:1}"
sleep .2
done
printf "\r"
}
<snippet end>
问题:我可以在脚本中添加哪些代码来检测故障或 control-c 并终止后台进程?
附加信息:我从包装器运行脚本,并在屏幕会话中运行它。
myprogram.sh $1 > >(tee -a /var/tmp/myprogram_install$DATE.log) 2> >(tee -a /var/tmp/myprogram_install$DATE.log >&
答案1
一种方法是:
quit=n
trap 'quit=y' INT
progress() {
SPIN='-\|/'
# Run the base 64 code in the background
echo $THECOMMAND | base64 -d|bash &
pid=$! # Process Id of the previous running command
i=0
while kill -0 $pid 2>/dev/null
do
if [ x"$quit" = xy ]; then
kill $pid
break
fi
i=$(( (i+1) %4 ))
# Print the spinning icon so the user knows the command is running
printf "\r$COMMAND:${SPIN:$i:1}"
sleep .2
done
printf "\r"
}