Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for a non-zero exit status of a command in Bash?

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:

  1. if [[ "$(is_git_repository)" != "0" ]] ; ... always evaluates to true (link)
  2. if [[ "$(is_git_repository)" -ne "0" ]] ; ... always evaluates to false
  3. if [[ "$(is_git_repository)" != 0 ]] ; ... always evaluates to true
  4. if [[ "$(is_git_repository)" -ne 0 ]] ; ... always evaluates to false
  5. if [[ ! "$(is_git_repository)" ]] ; ... always evaluates to true
  6. if !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?

like image 508
3cheesewheel Avatar asked Jul 03 '13 19:07

3cheesewheel


People also ask

How do you check exit status in bash?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

What is nonzero exit status?

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.

How do I check if a command is executed successfully in bash?

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.

How do I get exit status in shell?

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 $?


2 Answers

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?!

like image 72
3cheesewheel Avatar answered Oct 20 '22 18:10

3cheesewheel


Consider boolean shortcut instead of an if statement:

is_git_repository || echo you are NOT in a git repo
like image 21
Christoph2 Avatar answered Oct 20 '22 17:10

Christoph2