相关疑难解决方法(0)

为什么用errexit不能与命令列表一起使用?

如果我以普通用户身份运行以下shell脚本,它将按预期在第三行中止:

set -o errexit

echo foo > /bar
echo $?
Run Code Online (Sandbox Code Playgroud)

这是输出:

$ sh test1.sh 
test.sh: 3: test.sh: cannot create /bar: Permission denied
Run Code Online (Sandbox Code Playgroud)

但是,如果echo命令是复合列表的一部分,则执行失败的命令后将继续执行并显示退出代码:

set -o errexit

{ echo foo; } > /bar
echo $?
Run Code Online (Sandbox Code Playgroud)

这是输出:

$ sh test2.sh 
test.sh: 3: test.sh: cannot create /bar: Permission denied
2
Run Code Online (Sandbox Code Playgroud)

脚本为什么不会终止?另一方面,如果将花括号更改为括号,则其工作方式将与我期望的一样。

error-handling sh

8
推荐指数
1
解决办法
98
查看次数

标签 统计

error-handling ×1

sh ×1