Is there a way to easily commit a file to git if it has updated?

I want to take a list of files in a directory, write it to a text file, and commit it to git if it's changed. I assume this would involve a shell script that creates the list, then runs git add [file] then git commit -m "Updating" but I want to make sure it's not going to break if I run it in a cron script.



You can simply add all files that were updated with

git add -u <filepattern>

See manual:

Only match <filepattern> against already tracked files in the index rather than the working tree. That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.

If no <filepattern> is given, default to "."; in other words, update all tracked files in the current directory and its subdirectories.

This has the benefit of only adding files that were actually changed, and not adding any files that aren't indexed yet.

Then, it's just a matter of committing these changes like you proposed.

| improve this answer | |

This solution applies if the problem is to always add this single file even if you want to manually add other files:

There are hooks. You could for example make a shellscript in in the .git/hooks directory and name it pre-commit (don't forget to make it executable). In that file you could add something like git add -u $GIT_WORK_TREE/filename. This will always add that file automatically when commiting changes.

The $GIT_WORK_TREE part is referring to where you store your files.

| improve this answer | |

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.