105

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!"
branquito
  • 3,864
  • 5
  • 35
  • 60

4 Answers4

124

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; }
P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    Can you explain from where it was comming the message `numeric argument required`, and why I couldn't disable it with `2>/dev/null`? – branquito Jul 06 '14 at 16:28
  • 2
    Likely that `TRESHOLD` is empty. `echo` goes to stdout. So redirecting 2 will not work. You can print to stderr: `[[ $TRESHOLD =~ ^[0-9]+$ ]] || { echo 1>&2 "Threshold must be an integer value!"; exit $ERRCODE; }` – P.P Jul 06 '14 at 16:30
  • It's not empty, because when not provided, it has default value set. And I ment on my example `|| exit "message"`, without using `echo` – branquito Jul 06 '14 at 16:37
  • 4
    `exit` accepts only an option *integer* (exit code). So passing a string like `"message"` won't work. – P.P Jul 06 '14 at 16:44
  • 2
    Oh yes. I am stupid, I was confused because printing of my custom msg was side effect, of that error. – branquito Jul 06 '14 at 16:46
66

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.

konsolebox
  • 72,135
  • 12
  • 99
  • 105
7

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)
noonex
  • 1,975
  • 1
  • 16
  • 18
1

how about just echo a text and then exit:

echo "No Such File" && exit
vagitus
  • 264
  • 2
  • 10