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.
- You want to commit
- You don’t want to commit
- You accidentally prepared both for commit using
$ 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
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.
You still want to commit this part, so enter
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
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.