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
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"
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
}
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