如何使用Ctrl + C停止整个脚本而不仅仅是当前命令 [英] How to use Ctrl+C to stop whole script not just current command
问题描述
我有一个如下脚本:
for ((i=0; i < $srccount; i++)); do
echo -e "\"${src[$i]}\" will be synchronized to \"${dest[$i]}\""
echo -e $'Press any key to continue or Ctrl+C to exit...\n'
read -rs -n1
rsync ${opt1} ${opt2} ${opt3} ${src[$i]} ${dest[$i]}
done
如果响应读取命令按 Ctrl + C ,则整个脚本将停止,但是如果按 Ctrl + C 在运行 rsync
命令时,仅当前的 rsync
命令将停止,脚本将继续执行for循环.
If I press Ctrl+C in response to read command, the whole script will stop, but if press Ctrl+C while rsync
command is running, just current rsync
command will stop and the script will continue the for loop.
有什么方法可以告诉脚本,如果在 rsync
运行时用户是否按下 Ctrl + C ,请停止 rsync
并退出脚本本身?
Is there any way to tell the script if the user pressed Ctrl+C while rsync
is running, stop rsync
and exit from the script itself?
推荐答案
Ctrl + C 发送中断信号 SIGINT
.您需要通过内置的 trap
告诉bash在收到此信号时退出:
Ctrl+C sends the interrupt signal, SIGINT
. You need to tell bash to exit when it receives this signal, via the trap
built-in:
trap "exit" INT
for ((i=0; i < $srccount; i++)); do
echo -e "\"${src[$i]}\" will be synchronized to \"${dest[$i]}\""
echo -e $'Press any key to continue or Ctrl+C to exit...\n'
read -rs -n1
rsync ${opt1} ${opt2} ${opt3} ${src[$i]} ${dest[$i]}
done
您不仅可以在收到信号后退出,还可以做更多的事情.通常,信号处理程序会删除临时文件.有关更多详细信息,请参考 bash文档.
You can do more than just exiting upon receiving a signal. Commonly, signal handlers remove temporary files. Refer to the bash documentation for more details.
这篇关于如何使用Ctrl + C停止整个脚本而不仅仅是当前命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!