1

I want to run a command on bash that shows the output of git status, but only if something interesting is there. In other words: If everything is fine, I don't want the command to print anything. Basically I can achieve this by running:

if [[ $(git status -s) ]]; then git status; fi

The trick here is that the -s flag only outputs anything if there is something interesting, so it does exactly what I want to :-)

The only drawback is that if I run this in a directory that is not a git directory, I don't get an exit code not equal to 0. If I run git status or git status -s directly, both fail with exit code 128. But as soon as I do this within the if, the exit code is 0.

How can I enhance my script so that the exit code will be forwarded?

2
  • What exit code does git status -s give if nothing interesting has happened? Commented Aug 9, 2016 at 9:37
  • It returns 0, but the output itself is empty. Commented Aug 9, 2016 at 10:35

3 Answers 3

1

Do the exit status check within [[ too:

if [[ -n $(git status -s 2>/dev/null) ]]; then git status; fi
Sign up to request clarification or add additional context in comments.

2 Comments

or just if git status -s 2>/dev/null;then git status
Does git status -s return true even if nothing of interest has happened then?
1

You can use rev-parse in case the directory in not in git:

git rev-parse 2>/dev/null && { git status -s || git status; }

Comments

1

Just redirect to /dev/null and check if the output is empty or not:

[ -n "$(git status -s 2>/dev/null)" ] && git status

This will perform git status when the git status -s command runs successfully and its output is not empty, as per man test:

   -n STRING
          the length of STRING is nonzero

1 Comment

Unfortunately, this does not work: It correctly forwards the exit code, but does not suppress output if there is nothing interesting to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.