loading...

Partially Stage and Commit Changes in Git

grepliz profile image Liz Lam ・1 min read

Did you know you can partially stage and commit your changes in git?

Suppose you have file numbers.txt checked into your git repo with the following content:

1
2
3
4
5
6
7
8
9
10

Modify numbers.txt to look like this:

1 is for one.
2
3
4
5
6
7
8
9
10 is for ten.

Use git add -p to interactively decide which chunks of the modified file to commit.

Hit n to bypass the first chunk.

diff --git a/numbers.txt b/numbers.txt
index f00c965..32b6ae7 100644
--- a/numbers.txt
+++ b/numbers.txt
@@ -1,4 +1,4 @@
-1
+1 is for one.
 2
 3
 4
Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]? n

Hit y to stage the second chunk.

@@ -7,4 +7,4 @@
 7
 8
 9
-10
+10 is for ten.
Stage this hunk [y,n,q,a,d,K,g,/,e,?]? y

Now commit as normal.

$ git commit -m "Modify the 10th line"

You still have the changes to line 1 in your workspace but now your modification of line 10 is committed to the repo.

Posted on by:

grepliz profile

Liz Lam

@grepliz

I love open source, coffee and tinkering.

Discussion

markdown guide
 

I use that a lot. It's a great feature. Thanks for writing this nice post about it.
If you are working in ".NET Land", you might want to check out "git istage". It's really awesome if you want to stage individual line instead of entire chunks. github.com/terrajobst/git-istage

 

I've been using git for some time now and actually just recently discovered the -p flag. I'm not familiar with 'git istage', thanks for sharing! I will definitely check it out!