Reputation: 16231
I have the following Bash snippet in a larger Bash script:
if [ $COMMAND -le 1 ]; then
test $COMMAND -eq 0 && echo 1>&2 -e "\n${COLORED_ERROR} No command selected.${ANSI_NOCOLOR}"
echo ""
echo "Synopsis:"
echo " Script to simulate '$ModuleName' module testbenches with Riviera-PRO."
echo ""
echo "..."
test $COMMAND -eq 0 && exit 1 || exit 0
fi
```
The focus is on test $COMMAND -eq 0 && exit 1 || exit 0
Edit: The type of $COMMAND
is an integer.
Is there a better way to conditionally calculate the exit code?
I found a c ? a : b
operator on some websites talking about Bash arithmetic, but I couldn't get to work:
exit $(($COMMAND -eq 0 ? 1 : 0
Error message:
./tools/GitLab-CI/Riviera-PRO.run.sh: line 111: 1 -eq 0 ? 1 : 0 : syntax error in expression (error token is "0 ? 1 : 0 ")
Please note, $COMMAND
uses multiple integer values:
Upvotes: 1
Views: 1798
Reputation: 295619
Speaking only about how to correct your use of the ternary operator -- you need to use ==
, not -eq
, inside an arithmetic context:
retval=1
exit $(( (retval == 0) ? 1 : 0 ))
That said, if you want to exit with a successful status only if another command failed, that's as simple as:
! somecommand # run somecommand, and set $? to 0 only if it exited with an error
exit # use $? as our own exit status
Upvotes: 3