Oneliner for failing a bash command if it's in range

My current attempt at this is the following:

yarn audit || (mask=$? && [ $mask -lt 8 ])

This works, but is there a more nice & tidy approach than this? I mean, to me it doesn’t exactly scream “run this command and fail if the status code was >=8” For example, is there a way of avoiding the $? syntax when all you need to do is condition the status code once? I’m thinking along the lines of a single bracket expression such as [ $(yarn audit) -lt 8], which obviously isn’t what I want since $(yarn audit) return the output of the command, not the status code, but just to get what I’m aiming to do.

Any ideas?

If I understand the problem right, the script has set -e for the shebang line, but you only want to exit if the status from yarn audit is 8 or more, right? If so, you can simplify what you have slightly by skipping the mask variable:

yarn audit || [ $? -lt 8 ]

The main drawback is that you can’t do anything else with yarn’s status, because it gets immediately replaced by the status from the unit test, so try avoiding putting that into a subshell.

Now, I tend not to trust set -e to do the right thing, because its idea of when it’s appropriate to exit isn’t always what you expect or want.

I prefer explicit exit commands, something like this:

yarn audit || [ $? -lt 8 ] || {
echo "Audit failed" >&2
exit 1

This is more clumsy but clearer in intent:

yarn audit || if [ $? -ge 8 ]; then
echo "Audit failed" >&2
exit 1

I hope this helps.

1 Like

ah thanks, your suggestion worked @montana! our pipeline is building again