Home > Software engineering >  Bash - how to retrieve exit status of first command in an 'or' statement
Bash - how to retrieve exit status of first command in an 'or' statement

Time:02-18

In a script in gitlab I have the following statement: locust || true This is because I don't want gitlab CI to stop the execution of the stage if the locust command fails with some exit code. But how can I nevertheless retrieve the exit code of the locust statement

CodePudding user response:

If you place the command in an if statement instead of using || true, failure will not cause the script to exit and you'll be able to save the exit code.

if locust; then
    rc=0
else
    rc=$?
fi

echo locust exited with rc=$rc

PS: you can't just do if ! locust; then... because in that case, the ! reverses the logic of the exit code. You actually need the else block for the rc=$? to work the way you want.

PPS: Yeah, I like that other answer better, rc=0; locust || rc=$?... I should have thought of that!

CodePudding user response:

You could replace true with a variable assignment:

rc=0; locust || rc=$?

If like in a context with errexit set you want to make sure that the overall return code is always 0 even though the assignment miraculously fails somehow, just re-attach || true:

rc=0; locust || rc=$? || true

Going further:

If instead of the literal true you want some next command to be executed if the first one fails, then negate ! the variable assignment to make it fail in order to proceed to the evaluation of the second ||.

# For personal use only!
rc=0; first-cmd || ! rc=$? || next-cmd

But be cautious here (as always when connecting commands logically): Don't use this shortcut in a production context! Rather perform separate checks to see if all preconditions have been met to execute that command.

CodePudding user response:

Answering the ”Locust side” of the question: you can pass —exit-code-on-error 0 to only give a non-zero exit code if the run failed completely, not on failed responses.

(idk why this is not the default but changing it now would break stuff, so I probably won’t)

  • Related