If you are following my previous blog posts, you already know recently I’m doing some scripting using bash to minimize efforts in git functionalities. This post is also a part of that.
If you want to know current status of your working directory, what you need to do is simply run the command
git status in your console. If there are changes in your code, it will show the files which have been changed. Or if the directory is clean (there is nothing to commit), the output will be:
On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
So this is fine. But what if you want to do this from a bash script? You may need to do some work in your script based on this decision. How will you know if a directory is clean or not?
Parsing the output of git status is a bad idea because the output is intended to be human readable, not machine-readable. There’s no guarantee that the output will remain the same in future versions of Git or in differently configured environments. For this, Git provides the –porcelain option, which causes the output of git status –porcelain to be formatted in an easy-to-parse format for scripts, and will remain stable across Git versions and regardless of user configuration.
You can use empty output of
git status --porcelain as an indicator that there are no changes to be committed:
if [ -z "$(git status --porcelain)" ]; then # Working directory clean else # Uncommitted changes fi
That’s it. Now you can add your workflow logic as per your requirements inside those blocks where working directory is clean or not.