anon
anon

Reputation: 42627

in zsh, how do I do a conditional on the exit status of a program?

I want to do something like:

if [[ git status &> /dev/null ]]; then
   echo "is a git repo";
else
   echo "is not a git repo";
fi

except I don't know how to check the exit status. How do I fix this?

Upvotes: 32

Views: 31973

Answers (3)

sasquires
sasquires

Reputation: 376

Another form that I often use is the following:

git status &> /dev/null
if (( $? )) then
    desired behavior for nonzero exit status
else
    desired behavior for zero exit status
fi

This is slightly more compact than the accepted answer, but it does not require you to put the command on the same line as in gregseth's answer (which is sometimes what you want, but sometimes becomes too hard to read).

The double parentheses are for mathematical expressions in zsh. (For example, see here.)

Edit: Note that the (( expression )) syntax follows the usual convention of most programming languages, which is that nonzero expressions evaluate as true and zero evaluates as false. The other alternatives ([ expression ], [[ expression ]], if expression, test expression, etc.) follow the usual shell convention, which is that 0 (no error) evaluates as true and nonzero values (errors) evaluate as false. Therefore, if you use this answer, you need to switch the if and else clauses from other answers.

Upvotes: 1

orip
orip

Reputation: 75427

The variable $? contains the last commands return code

EDIT: precise example:

git status &> /dev/null
if [ $? -eq 0 ]; then
  echo "git status exited successfully"
else
  echo "git status exited with error code"
fi

Upvotes: 38

gregseth
gregseth

Reputation: 13408

Simply like that

if git status &> /dev/null
then
   echo "is a git repo";
else
   echo "is not a git repo";
fi

Or in a more compact form:

git status &> /dev/null && echo "is a git repo" || echo "is not a git repo"

Upvotes: 28

Related Questions