括号内的`exit`不会退出脚本 [英] `exit` inside parentheses doesn't exit script

查看:64
本文介绍了括号内的`exit`不会退出脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题.为什么这不符合我的想法:

Here is a simple question. Why does this not behave the way I think it would:

(echo "Test 1"; exit) && echo "Test 2"

...或...

VAR1=1
VAR2=2
[ $VAR1 == $VAR2 ] || (echo '$VAR1 does not equal $VAR2, exiting.'; exit)
echo -e 'Well, I\'m still alive yo!'

运行这两个代码片段中的任何一个都将导致脚本执行继续,尽管使用了显式的exit命令.

Running either of those two snippets will result in script execution continuing despite an explicit exit command.

显然括号由于某种原因影响了命令,我的问题是为什么?

Obviously the parentheses are affecting the command for some reason, my question is why?

推荐答案

括号在子外壳中执行其内容,因此退出的是子外壳.

The parentheses execute their contents in a subshell, it is therefore the subshell that exits.

通常,使用另一个&&或使用{}而不是()可以达到相同的效果.

You would usually achieve the same effect either with another && or using {} instead of ().

{ echo "Test 1"; exit; } && echo "Test 2"

echo "Test 1" && exit && echo "Test 2"

这篇关于括号内的`exit`不会退出脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆