exit with error message in bash (oneline)

BashMessageExit

Bash Problem Overview


Is it possible to exit on error, with a message, without using if statements?

[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit ERRCODE "Threshold must be an integer value!"

Of course the right side of || won't work, just to give you better idea of what I am trying to accomplish.

Actually, I don't even mind with which ERR code it's gonna exit, just to show the message.

EDIT

I know this will work, but how to suppress numeric arg required showing after my custom message?

[[ $TRESHOLD =~ ^[0-9]+$ ]] || exit "Threshold must be an integer value!"

Bash Solutions


Solution 1 - Bash

exit doesn't take more than one argument. To print any message like you want, you can use echo and then exit.

    [[ $TRESHOLD =~ ^[0-9]+$ ]] || \
     { echo "Threshold must be an integer value!"; exit $ERRCODE; }

Solution 2 - Bash

You can use a helper function:

function fail {
    printf '%s\n' "$1" >&2 ## Send message to stderr.
    exit "${2-1}" ## Return a code specified by $2, or 1 by default.
}

[[ $TRESHOLD =~ ^[0-9]+$ ]] || fail "Threshold must be an integer value!"

Function name can be different.

Solution 3 - Bash

Using exit directly may be tricky as the script may be sourced from other places. I prefer instead using subshell with set -e (plus errors should go into cerr, not cout) :

set -e
[[ $TRESHOLD =~ ^[0-9]+$ ]] || \
     (>&2 echo "Threshold must be an integer value!"; exit $ERRCODE)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbranquitoView Question on Stackoverflow
Solution 1 - BashP.PView Answer on Stackoverflow
Solution 2 - BashkonsoleboxView Answer on Stackoverflow
Solution 3 - BashnoonexView Answer on Stackoverflow