Fail a command in -e mode only for some nonzero exit statuses

Our company is using Travis CI and our team want to add a yarn audit check to my test script for HIGH or CRITICAL vulnerabilities. When calling yarn audit Travis returned status code of a bitmask of vulnerability levels, so that for example if you have moderate (4) and critical (16) levels, you get 20 back. And I want to fail my script if there are at least any high alerts, so if status >= 8.

Travis is setup so that a list of commands are run in sequence, aborting when there’s a non-zero status code, so basically a set -e setup I guess.

My current attempt at this is the following:

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

it doesn’t exactly say “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)].

for bracket expression is there anything I can do cleaner? need help thank you…

Hey,

Kind of hard to understand your issue, but let me take a deep dive.

Now if I understand right, the script has set -e set, but you only want to exit if the status from yarn audit is 8 or more, right? If so, you can just simply 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, in turn causing it to be linear, because it gets immediately replaced by the status from the [ ] (bracket expression) test.

Secondly you can avoid putting that code snippet in a subshell, you’d have to use { ;} instead of ( ), the upside is you can use it later.

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

Once you do that, it should fix your bracket expression issue – with that being said there are cleaner methods of doing this, I would be happy to DM you about. The current setup you have seems redundant to a degree, and could be setup better. If you let me see the .travis.yml file I’ll help you clean this up and get it working cleaner.

Montana Mendy
Software Engineer
Travis CI

2 Likes

this worked perfectly! as usual @montana thank you

No problem, glad I could be of help!

1 Like