Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.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 错误陷阱和命令替换_Bash_Shell - Fatal编程技术网

Bash 错误陷阱和命令替换

Bash 错误陷阱和命令替换,bash,shell,Bash,Shell,运行test.sh: #!/bin/bash set -eE trap "echo 'in trap'" ERR var=$(bad_command) #!/bin/bash set -eE trap "echo 'in trap'" ERR echo $(bad_command) 输出为: ./test.sh: line 7: bad_command: command not found in trap ./test2.sh: line 8: bad_command: command n

运行
test.sh

#!/bin/bash
set -eE
trap "echo 'in trap'" ERR
var=$(bad_command)
#!/bin/bash
set -eE
trap "echo 'in trap'" ERR
echo $(bad_command)
输出为:

./test.sh: line 7: bad_command: command not found
in trap
./test2.sh: line 8: bad_command: command not found
# line with whitespace printed
运行
test2.sh

#!/bin/bash
set -eE
trap "echo 'in trap'" ERR
var=$(bad_command)
#!/bin/bash
set -eE
trap "echo 'in trap'" ERR
echo $(bad_command)
输出为:

./test.sh: line 7: bad_command: command not found
in trap
./test2.sh: line 8: bad_command: command not found
# line with whitespace printed
为什么在
test2.sh
中没有触发陷阱?

不同之处仅在于
var=$(badcommand)
echo$(badcommand)
将不正确的退出代码设置到shell。第二种情况很明显,
echo
没有设置不正确的退出代码,因为它是一个单独运行的进程,能够根据成功/失败设置自己的代码。由于
echo
似乎已正确退出,但它没有任何打印输出,因此它向shell打印了一个代码
0
,从而掩盖了命令替换导致的
命令未找到
错误

您只需尝试在shell中运行,而不使用
set-e
和定义的陷阱

var=$(badcommand); echo $?
bash: badcommand: command not found...
127
echo $(badcommand); echo $?
bash: badcommand: command not found...

0

第一个触发陷阱,下一个不触发。

相关:。在shell中的大多数位置,退出状态等于执行的最后一个命令。因此,在
echo$(bad_command)
中执行的最后一个命令是
echo
,命令成功。没有理由去陷阱。