![为什么括号返回退出状态而不是大括号](https://linux22.com/image/187427/%E4%B8%BA%E4%BB%80%E4%B9%88%E6%8B%AC%E5%8F%B7%E8%BF%94%E5%9B%9E%E9%80%80%E5%87%BA%E7%8A%B6%E6%80%81%E8%80%8C%E4%B8%8D%E6%98%AF%E5%A4%A7%E6%8B%AC%E5%8F%B7.png)
据我所知,括号会导致命令在子 shell 中运行,大括号会导致命令组合在一起,但不会在子 shell 中运行。
当我用括号运行时:
no_func || (
echo "there is nothing"
exit 1
)
echo $?
这将返回退出状态:
/Users/myname/bin/ex5: line 34: n_func: command not found
there is nothing
1
但是当我使用大括号时:
no_func || {
echo "there is nothing"
exit 1
}
echo $?
这不会返回退出状态。
/Users/myname/bin/ex5: line 34: no_func: command not found
there is nothing
但为什么一个返回退出状态而另一个不返回呢?
答案1
查看命令执行轨迹(set -x
)。带大括号:
+ no_func
./a: line 3: no_func: command not found
+ echo 'there is nothing'
there is nothing
+ exit 1
exit
退出(子)shell。由于大括号不会创建子 shell,因此exit
会退出主 shell 进程,因此它永远不会到达它将运行的位置echo $?
。
答案2
当您使用大括号时,脚本在到达echo $?
脚本之前会以状态 1 退出。
带子外壳的变体:
$ ./script1.sh
./script1.sh: line 3: no_func: command not found
there is nothing
1 # <-- exit status of subshell
$ echo $?
0 # <-- exit status of script
带大括号的变体:
$ ./script2.sh
./script2.sh: line 3: no_func: command not found
there is nothing # <-- the script exits with 1 after this line
$ echo $?
1 # <-- exit status of script