我试图在 bash 脚本中有一个交互式程序:
my_program
Run Code Online (Sandbox Code Playgroud)
我希望能够用 'Ctrl + c' 关闭它。但是当我这样做时,我的脚本也正在关闭。
我知道。
trap '' 2
my_program
trap 2
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,我无法my_program
用 Ctrl + c关闭。
您知道如何在程序上允许 Ctrl + c ,但不关闭运行它的脚本吗?
编辑:添加示例
#!/bin/bash
my_program
my_program2
Run Code Online (Sandbox Code Playgroud)
如果我使用 Ctrl + c 关闭my_program
,my_program2
则永远不会执行,因为整个脚本已退出。
mos*_*svy 13
您应该使用trap true 2
或trap : 2
代替trap '' 2
。这就是 bash shell 中的“帮助陷阱”所说的:
如果 ARG 是空字符串,则 shell及其调用的命令将忽略每个 SIGNAL_SPEC 。
例子:
$ cat /tmp/test
#! /bin/sh
trap : INT
cat
echo first cat killed
cat
echo second cat killed
echo done
$ /tmp/test
<press control-C>
^Cfirst cat killed
<press control-C>
^Csecond cat killed
done
Run Code Online (Sandbox Code Playgroud)
Mar*_*ick 12
您可以通过将陷阱命令-
作为其操作参数来将陷阱重置为其默认值。如果您在subshell 中执行此操作,则不会影响父 shell 中的陷阱。在您的脚本中,您可以对需要使用 Ctrl-C 中断的每个命令执行此操作:
#!/bin/bash
# make the shell (and its children) ignore SIGINT
trap '' INT
.
.
.
# but this child won't ignore SIGINT
(trap - INT; my_program)
# the rest of the script is still ignoring SIGINT
.
.
.
Run Code Online (Sandbox Code Playgroud)