I have a script which runs multiple commands and I want to return a 0 exit code if all is well, 1 if not. In the first iteration, my script looks like this:
make foo
make bar
The problem is, if make foo
failed, my script does not return an exit code of 1 because that exit code was overwritten by make bar
, which passed.
Second iteration:
RC=0
make foo || RC=1
make bar || RC=1
exit $RC
This works, but it is cumbersome. Is there a better way?
Update
To clarify, I want to run all the commands no matter what. So, if make foo
failed, I still want to run make bar
after that. This is part of a pipeline, so I want to run all commands, only to return the code at the end where 0=OK, 1=Some command failed.
CodePudding user response:
You can use an ERR
trap to update the value of RC
if a command fails.
trap 'RC=1' ERR
...
exit $RC
If RC
never gets set, making the final command exit
with no argument, the exit status of the last command is used, but that's 0 by virtue of the trap never being triggered.