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 provides a command to exit a script if errors occur, the exit command. The argument N (exit status) can be passed to the exit command to indicate if a script is executed successfully (N = 0) or unsuccessfully (N != 0). If N is omitted the exit command takes the exit status of the last command executed.
By convention, an exit code of zero indicates that the command completed successfully, and non-zero means that an error was encountered. The status code can be used to find out why the command failed.
After a function returns, $? gives the exit status of the last command executed in the function. This is Bash's way of giving functions a "return value." [ 1] Following the execution of a pipe, a $? gives the exit status of the last command executed.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With