Reputation: 9623
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?
Upvotes: 16
Views: 17302
Reputation: 139
Consider boolean shortcut instead of an if
statement:
is_git_repository || echo you are NOT in a git repo
Upvotes: 5
Reputation: 9623
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?!
Upvotes: 17