Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 当控制+;在shell脚本中按下C键?_Bash_Macos_Shell_Cmd_Command Line Interface - Fatal编程技术网

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