Bash 当控制+;在shell脚本中按下C键?
我有一个脚本可以做一些工作。它以一种恰当的方式进行,但需要一段时间才能结束。因为我想模拟“作业正在运行”,所以我添加了一个微调器光标动画Bash 当控制+;在shell脚本中按下C键?,bash,macos,shell,cmd,command-line-interface,Bash,Macos,Shell,Cmd,Command Line Interface,我有一个脚本可以做一些工作。它以一种恰当的方式进行,但需要一段时间才能结束。因为我想模拟“作业正在运行”,所以我添加了一个微调器光标动画 #!/bin/bash spinner & SPINNER_PID=$! # a lot of stuff going on here... # takes some time to finish kill $SPINNER_PID &>/dev/null printf "All done" 我在脚本开始时调用它,然后我将该函数
#!/bin/bash
spinner &
SPINNER_PID=$!
# a lot of stuff going on here...
# takes some time to finish
kill $SPINNER_PID &>/dev/null
printf "All done"
我在脚本开始时调用它,然后我将该函数的PID分配给一个变量,当所有操作完成后,我简单地杀死它以停止动画
#!/bin/bash
spinner &
SPINNER_PID=$!
# a lot of stuff going on here...
# takes some time to finish
kill $SPINNER_PID &>/dev/null
printf "All done"
功能定义:
spinner() {
local i sp n
sp='/-\|'
n=${#sp}
while sleep 0.1; do
printf "%s\b" "${sp:i++%n:1}"
done
}
如果我不打断的话,一切正常
想象一下,我想通过调用Control+C
来取消我的长任务。它取消了,但微调器显然仍然会动画,因为它没有注意到一个无限循环
当脚本被手动取消并且无法达到
kill$SPINNER\u PID&>/dev/null
时,如何杀死它?似乎有一个名为trap
的语句,它允许您在按下Ctrl-C
时运行代码。对此有很好的解释,而且
说明如何在Ctrl-C
上运行函数
trap your_func INT