I have a script that checks the exit status of the following function:
function is_git_repository {
git branch &> /dev/null
}
Which returns 0
if you're in a git repo, and 128
if you're not.
I have no problem testing to see if the return value is 0
; the following works as expected:
if is_git_repository ; then
echo you are in a git repo
else
echo you are NOT in a git repo
fi
But it's when I'm trying to test for an exit status that is anything OTHER than 0
when I'm running into problems. I've tried the following, but none of them work:
if [[ "$(is_git_repository)" != "0" ]] ; ...
always evaluates to true (link)if [[ "$(is_git_repository)" -ne "0" ]] ; ...
always evaluates to falseif [[ "$(is_git_repository)" != 0 ]] ; ...
always evaluates to trueif [[ "$(is_git_repository)" -ne 0 ]] ; ...
always evaluates to falseif [[ ! "$(is_git_repository)" ]] ; ...
always evaluates to trueif !is_git_repository ; ...
just echoes the command back to me, but without the bang (wtf?) What is the correct way to check for a non-zero exit status of a command in an if statement?
To display the exit code for the last command you ran on the command line, use the following command: $ echo $?
A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so there is one well-defined way to indicate success and a variety of ways to indicate various failure modes. When a command terminates on a fatal signal whose number is N , Bash uses the value 128+ N as the exit status.
Now, every command run in bash shell returns a value that's stored in the bash variable “$?”. To get the value, run this command. $ echo $? If a command succeeded successfully, the return value will be 0.
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. $ echo $?
I soon figured out that if ! is_git_repository ; then ...
works as intended (look under 7.1.2.1. Testing exit status in Introduction to if), but why? I would have expected that #1 would work at the very least, but I don't know why it doesn't.
Also, what is up with #6?!
Consider boolean shortcut instead of an if
statement:
is_git_repository || echo you are NOT in a git repo
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