'Bash - how to retrieve exit status of first command in an 'or' statement

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



Solution 1:[1]

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.

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Cyberwiz