考虑:
$ cat b.sh
#!/bin/bash
trap 'echo $$ was interrupted' INT
read foo
echo done
$ ./b.sh
^C27104 was interrupted
^C27104 was interrupted
^C27104 was interrupted
done
$
(ctrl-c被击中3次,然后是ctrl-d)
我希望read
在执行陷阱后中止。有没有一种干净的方法来实现这一目标?
答案 0 :(得分:9)
似乎没有立即中断是Bash非POSIX扩展(请参阅Bash内置源read_builtin
中的read.def
(查找posixly_correct
))。
您可以通过强制Ctrl+C
的POSIX行为(通过设置read
环境变量)来覆盖此行为并退出第一个POSIXLY_CORRECT
:
#!/bin/bash
trap 'echo $$ was interrupted' INT
POSIXLY_CORRECT=1 read foo
echo done