如果不是bash,则与sys.exit()的bash版本合为一行 [英] Bash if else then in one line with bash version of sys.exit()
问题描述
我正在运行此bash命令:
I am running this bash command:
xe pbd-unplug uuid=$PBDUUID
如果结果存在-即如果变量PBDUUID
不为空,则我想运行另一个命令:
If the result exists - i.e. if the variable PBDUUID
is not empty then I would like to run another command:
xe sr-forget uuid=$SRUUID
但是,如果变量为空,那么我想打印一条错误消息
However, if the variable is blank then I would like print an error message
Error: No PBD.
,然后脚本立即退出(类似于Python中的sys.exit()
).
and for the script to exit immediately (similar to sys.exit()
in Python).
是否有一种方法可以将此if else then
合并为一行?另外,sys.exit()
的bash等效项是什么?
Is there a way to combine this if else then
into one line? Also, what is the bash equivalent of sys.exit()
?
其他信息/评论:
关于Dilettant的评论,是的,该方法(if [ -z ${PBDUUID} ]; then
)也将起作用.我不知道.谢谢你看起来很直观.
Regarding comment by Dilettant, yes that approach (if [ -z ${PBDUUID} ]; then
) will also work. I was not aware of it. Thanks for this. That seems quite intuitive.
推荐答案
if xe pbd-unplug uuid="$PBDUUID"; then xe sr-forget "uuid=$SRUUID"; else echo "Error: No PBD."; exit 1; fi
更容易理解的是,
if xe pbd-unplug uuid="$PBDUUID"; then
xe sr-forget "uuid=$SRUUID"
else
echo "Error: No PBD." >&2
exit 1
fi
顺便说一句,如果您的目标是检查变量是否为空,则该变量应类似于以下内容:
BTW, if your goal is to check whether a variable is blank, that would look more like the following:
if [ -z "$PDBUUID" ]; then
xe pdb-unplug uuid="$PDBUUID" && xe sr-forget "uuid=$SRUUID"
else
echo "Error: No PBD." >&2
exit 1
fi
如果exit
并没有按照您的预期进行,则该代码可能在子外壳中运行,因此exit
退出了该子外壳,而不是整个脚本.请参阅
If exit
doesn't do as you intend, then this code is presumably running in a subshell, and thus exit
is exiting that subshell rather than your script as a whole. See SubShell or the "Actions that Create a Subshell" section of the processtree bash-hackers.org page.
这篇关于如果不是bash,则与sys.exit()的bash版本合为一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!