This seems to be working but also is quite horrendously slow and seems a little hacky to me.


for currentFile in $(git status | grep "modified:" | cut -c 14-)
    gitDiff=$(git diff "$currentFile")
    if [ "$gitDiffStr" == "[]" ]
        echo match
        echo git checkout "$currentFile"
        git checkout "$currentFile"
  • 1
    \$\begingroup\$ what's wrong with git checkout -- .? \$\endgroup\$ – Vogel612 Feb 8 '18 at 15:26
  • \$\begingroup\$ That would reset all of the files. I only wanted to reset the ones that show as changed but have no changes according to git diff. I'd like to maintain the ones that have genuine changes. This is definitely not explained well enough in my post, though. \$\endgroup\$ – Geesh_SO Feb 8 '18 at 15:39
  • 2
    \$\begingroup\$ Same question on stackoverflow: stackoverflow.com/q/48688292/7552 \$\endgroup\$ – glenn jackman Feb 8 '18 at 15:44
  • \$\begingroup\$ I wonder if you really need to parse the git status output; does git diff --name-only list such files? \$\endgroup\$ – 301_Moved_Permanently Feb 8 '18 at 16:51

The slowness

The slowness most probably comes from executing multiple git diff commands. A faster way might be using a programming language with a Git library that would let you run a single git diff command, and iterate over the entries of the diff to find the empty ones.

The hacky part

This is hacky:

git status | grep "modified:" | cut -c 14-

The output of the git status is not API, and may also be subject to aliases and user settings. It's not safe to use. When parsing the output of Git commands, look for a --porcelain option to make it safe.

Another hacky part is changing the value of IFS. It's not a huge problem, but it's good to minimize the scope of the change, typically by using it in the form of IFS=... cmd, which would limit the effect of the change to the execution of the cmd command.

Lastly, some minor style issues:

  • The $gitDiffStr variable is pointless, you can simply inline it.
  • The == operator within a [ ... ] is undocumented. Use = instead.

Alternative implementation

Applying the above suggestions, this is less hacky, and probably just as slow:

git status --porcelain -z | grep -z '^ M' | while IFS= read -r -d '' path0; do
    gitDiff=$(git diff "$path")
    if [ "$gitDiff" = "" ]; then
        echo git checkout "$currentFile"
        git checkout "$currentFile"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.