Reputation: 150624
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?
Upvotes: 1
Views: 394
Reputation: 42017
Do the exit status check within [[
too:
if [[ -n $(git status -s 2>/dev/null) ]]; then git status; fi
Upvotes: 1
Reputation: 289685
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
Upvotes: 1
Reputation: 13249
You can use rev-parse
in case the directory in not in git
:
git rev-parse 2>/dev/null && { git status -s || git status; }
Upvotes: 1