在捕获中断后如何使Bash的读取中止?

时间:2017-12-07 18:28:28

标签: bash signals

考虑:

$ 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在执行陷阱后中止。有没有一种干净的方法来实现这一目标?

1 个答案:

答案 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