Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an error in Bash?

Tags:

bash

How do I throw an error in bash to get in my catch clause (I'm not sure what this expression is actually called)

{
  # ...
  if [ "$status" -ne "200" ]
    # throw error
  fi
} || {
  # on error / where I want to get if status != 200
}

I know I just could use a function but this case made me curious if it would be possible to do this

like image 684
boop Avatar asked Dec 04 '15 20:12

boop


2 Answers

There are multiple ways to do something similar:

use subshells (might not be the best solution if you want to set parameters etc...)

(
if [[ "$status" -ne "200" ]]
then
    exit 1
fi 
) || (
  # on error / where I want to get if status != 200
  echo "error thrown"
)

use an intermediate error variable (you can catch multiple errors by setting different numbers. Also: less indentation depth)

if [[ "$status" -ne "200" ]]
then
    error=1
fi

if [ $error != 0 ]
then
    echo "error $error thrown"
fi

use immediately the exit value of your test (note that I changed -ne to -eq)

[[ "$status" -eq "200" ]] || echo "error thrown"
like image 131
Chris Maes Avatar answered Oct 14 '22 04:10

Chris Maes


One way to do it is with just exit as shellter mentions, but you have to create a subshell for that work (which exists on the exit). To do this, replace the curly brackets with parentheses.

The code will be

(
 # ...
 if [ "$status" -ne "200" ]
    exit 1
 fi
) || {
   # on error / where I want to get if status != 200
}
like image 27
toth Avatar answered Oct 14 '22 05:10

toth