Skip to main content

How to commit only part of a file?

·231 words·2 mins
Git Guides
Yuriy Semyenkov
Author
Yuriy Semyenkov
DevOps, tech, geek, mentor
Table of Contents

TL;DR;
#

git add -p

A bit more detail
#

The git add -p (or --patch) command goes through all files and asks about each change, what you want to do with it:

❯ git add -p
diff --git a/ansible/file.yml b/ansible/file.yml
index 73f6b4d..899610f 100644
--- a/ansible/file.yml
+++ b/ansible/file.yml
@@ -52,7 +52,8 @@
       loop:
-        - "service"
+        - "node_modules"
+        - "systemd_templates"
       
(1/1) Stage this hunk [y,n,q,a,d,e,?]?

Then it’s an interactive input. Well, the most important are “y” and “n" — to add these changes to the index or skip them. There are options to skip or add “to the end of the file”. It can also be used as git add -p filename.

Reminder, the index in git is a list of files that will be committed.

Importantly, this action adds our change only to the index. It still needs to be committed.

How else can it be used?
#

As I wrote here, I always used either git add . or git add <filename>. But there’s a catch:

with git add ., extra files about which you might have forgotten can get into the index, and then into the commit

Here, git add -p allows you to more consciously (thoughtfully) go through the files before adding them to the index.

Also, a reminder that to remove a file from the index, you can use the command git reset filename.

Related

What do I listen to when I work
·258 words·2 mins
Productivity
Difference between $VAR and ${VAR}?
·138 words·1 min
Linux