How can I run a command in bash
or any other bash-like shell only if another command outputs something?
I am working on an API that updates the cache storage of a tool and commits the updated cache to GitHub. What I want to do is, after rebuilding the cache, I want to check if git diff HEAD ./path/to/cache
outputs something and if it does, then I want to run git add ./path/to/cache
.
Unfortunately, this doesn't work:
git diff HEAD ./path/to/cache && git add ./path/to/cache
I think because the first command doesn't return false
or exit and instead outputs an empty string or nothing at all. So, what's the correct way to achieve this in bash
?
CodePudding user response:
Use the --exit-code
option, which causes git diff
to exit with 0 if there are no diffs and 1 otherwise. Then you can ignore the output.
git diff --exit-code HEAD ./path/to/cache || git add ./path/to/cache
CodePudding user response:
The answer posted by @chepner is definitely the best for my use case. But my question was originally for any use case. If you want to achieve the same behavior for any other commands, you can use the grep
command to check if the first command outputs anything.
git diff HEAD ./path/to/cache | grep -q . && git add ./path/to/cache