DEV Community

Liz Lam
Liz Lam

Posted on

Partially Stage and Commit Changes in Git

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
Enter fullscreen mode Exit fullscreen mode

Modify numbers.txt to look like this:

1 is for one.
2
3
4
5
6
7
8
9
10 is for ten.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now commit as normal.

$ git commit -m "Modify the 10th line"
Enter fullscreen mode Exit fullscreen mode

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

Top comments (3)

Collapse
 
n_develop profile image
Lars Richter

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

Collapse
 
grepliz profile image
Liz Lam

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!

Collapse
 
msamgan profile image
Mohammed Samgan Khan

nice insight...