3cheesewheel 3cheesewheel - 1 year ago 118
Bash Question

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
if you're in a git repo, and
if you're not.

I have no problem testing to see if the return value is
; the following works as expected:

if is_git_repository ; then
echo you are in a git repo
echo you are NOT in a git repo

But it's when I'm trying to test for an exit status that is anything OTHER than
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?

Answer Source

I soon figured out that if ! is_git_repository ; then ... works as intended (look under 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?!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download