0

I have a few Git repositories that get updated automatically by a script. One of the tasks of the script is to run npm install for every repository (the repositories contain Node.js projects).

From time to time this results in an updated package-lock.json file, and I would like to commit it automatically if it was changed.

Of course I can simply run:

git add package-lock.json
git commit -m 'Update dependencies.'

But this fails, if the file was not updated: While git add simply does nothing and exits with return code 0, the git commit call fails with exit code 1. How can I do this in a way that this only happens if the file was actually updated?

In other words: If the file was not updated, I do not want the git add/git commit part to happen. How could I do this?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425

3 Answers3

3

You can use git diff --exit-code --quiet <filename> to check if the file was modified. If the returnvalue is 1, it was changed:

if ! git diff --exit-code --quiet package-lock.json ; then
    git add package-lock.json
    git commit -m 'Update dependencies.'
fi

That being said, there is no need to check the file beforehand and just running the lines

git add package-lock.json
git commit -m 'Update dependencies.' || true

will have the same effect, and a return value of 0

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • this is actually better than my proposal, as it doesn't involve using another executable to analyse output. I guess you can check for any file being modified with just `git diff --exit-code --quiet` right? – pqnet Jul 04 '18 at 13:50
1

you can use git status --porcelain | grep . >/dev/null and check grep exit state to see if your working tree has modification

It works because git status --porcelain will output all changes, but no output in case the working tree is clean. grep . will exit success if it finds a match, fail if it doesn't, and . is regular expression for "anything"

pqnet
  • 6,070
  • 1
  • 30
  • 51
1

You can also use git diff <filename>, this will output the changes (if any) or nothing if no changes.

HRK44
  • 2,382
  • 2
  • 13
  • 30
  • 1
    AFAIK `git show` would show the changes in the last commit, not in the current working tree compared to the head. `git diff` is probably the command you meant – pqnet Jul 04 '18 at 13:56
  • 1
    yes, meant git diff :D Nils werner answer is more complete tho – HRK44 Jul 04 '18 at 13:58