Golo Roden
Golo Roden

Reputation: 150892

Figure out (using Git) whether a file was updated

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?

Upvotes: 0

Views: 523

Answers (3)

HRK44
HRK44

Reputation: 2782

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

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36835

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

Upvotes: 3

pqnet
pqnet

Reputation: 6608

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"

Upvotes: 1

Related Questions