Prevent a specific change from being committed

In a nutshell: Use git reset -p to pick which changes you want to unstage. When a change is unstaged, it will not be part of your next commit.

Problem

  • You want to commit add-this-file.
  • You don’t want to commit do-not-change.
  • You accidentally prepared both for commit using git add.
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	new file:   add-this-file
	modified:   do-not-change

Solution

Unstage the unwanted changes

You can use git reset -p to unstage specific changes. When a change is unstaged, it will not be part of your next commit.

$ git reset -p
diff --git a/add-this-file b/add-this-file
new file mode 100644
index 0000000..7a254bf
--- /dev/null
+++ b/add-this-file
@@ -0,0 +1 @@
+This text should be committed.
Unstage this hunk [y,n,q,a,d,/,e,?]?

You still want to commit this part, so enter n.

diff --git a/do-not-change b/do-not-change
index 5adcd3d..dbf69fd 100644
--- a/do-not-change
+++ b/do-not-change
@@ -1 +1,3 @@
 This is a text file.
+
+This is a change I don't want to commit.
Unstage this hunk [y,n,q,a,d,/,e,?]?

You want to avoid this change from being committed, so enter y. New status:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	new file:   add-this-file

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   do-not-change

Optional: discard the changes

The file do-not-change is now listed as “not staged for commit”. However, the file itself still contains the text This is a change I don't want to commit. You can do a couple of things at this point:

  • Option 1: Keep these changes without committing them. No further action needed.
  • Option 2: Discard all changes to this specific file. Run git checkout -- do-not-change. Other files will not be affected.
  • Option 3: Discard changes to all files are not marked to be committed. Run git checkout -- .. This will only affect modified files, not newly created files.