Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit with error message in bash (oneline)

Tags:

bash

exit

message

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!" 
like image 949
branquito Avatar asked Jul 06 '14 16:07

branquito


People also ask

How do you exit a bash script error?

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.

What is exit 0 in bash script?

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.

What is exit $?

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.

How do you check exit status in bash?

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.


2 Answers

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; } 
like image 63
P.P Avatar answered Nov 13 '22 09:11

P.P


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.

like image 32
konsolebox Avatar answered Nov 13 '22 08:11

konsolebox