W R W R - 5 months ago 13
Linux Question

Bash if else then in one line with bash version of sys.exit()

I am running this bash command:

xe pbd-unplug uuid=$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.


and for the script to exit immediately (similar to
sys.exit()
in Python).

Is there a way to combine this
if else then
into one line? Also, what is the bash equivalent of
sys.exit()
?

Additional Information/Comment:

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.

Answer
if xe pbd-unplug uuid="$PBDUUID"; then xe sr-forget "uuid=$SRUUID"; else echo "Error: No PBD."; exit 1; fi

More readably, that is:

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

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.