I have a complex script where I generally test each command individually for success. However, there are cases where I have to carry out a sequence of simple operations, and I'd prefer to get an exit status from the entire sequence, without bothering to check each command individually.
This is my first attempt, with some arbitrary commands:
#!/bin/bash
if ! (
set -e
cd test
touch foo
chown root:root foo)
then
echo "subshell failed"
else
echo "subshell completed"
fi
The set -e
was meant to ensure that the subshell exited with failure when the first failure was encountered, but this doesn't work. In this case, if directory test
doesn't exist, the script simply creates foo
in the current directory, and then fails on the chown
.
What's the right way to do this? In other words, echo 'subshell completed' only if all 3 commands completed without error?
set -e
covered in BashFAQ #105.a && b && c
, considera || exit; b || exit; c || exit
-- that way you can decide to modify behavior for any particular element without needing to worry about breaking a chain. (When in a function but not in a subshell, replace|| exit
with|| return
as appropriate).if (set -e; false; true); then echo success; else echo failed; fi
.