2

My preferred routine is to stage and commit my changed files all at once:

git commit -a
# enter commit message via editor

This works great when all of my changes are related to each other. However, when there are several unrelated changes (i.e. I forgot to make commits for each one), it makes for a lengthy commit message. In these cases, I'd rather have an individual commit message for each file, or even a separate commit message per change when there are multiple unrelated changes within a file. How can I do that?


Note: Difference between this and How do I commit only some files?

My question is different because it also addresses multiple commits within a file.

Community
  • 1
  • 1
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99

3 Answers3

5

If you want to add a whole file, then use

git add file.txt

If you have separate changes within the same document that you want in separate commits, use a patch for selecting hunks

git add -p

When in interactive mode, if the hunks are too big, then you can split them by pressing S

After splitting, if you find that the hunks still aren't granular enough, then see my answer about manually editing it to create precision patches.

Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
2

Simply run git stage and git commit separately for each file:

git stage file1.txt
git commit
# use editor to type reasons for changing file1.txt

git stage file2.txt
git commit
# use editor to type reasons for changing file2.txt

See Jeff Puckett II's answer for how to commit sub-file level changes.

Community
  • 1
  • 1
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
2

You can also do a git add -i for an interactive staging, which lets you have fine grained control over what is introduced into the index. There is a full explanation of this option in the help output for git add and also a nice writeup at https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging

David Neiss
  • 8,161
  • 2
  • 20
  • 21