How to stage selected parts of the changes?

git add -p

To stage only selected parts of your changes use git add -p.

Git will show parts of your changes one by one and let you decide what to do with that change.

The available actions for the given hunk are:
 y - stage this hunk
 n - do not stage this hunk
 q - quit staging hunks
 a - stage this and all the remaining hunks in the file
 d - do not stage this hunk nor any of the remaining hunks in the file
 K - leave this hunk undecided, see previous hunk
 g - select a hunk to go to
 / - search for a hunk matching the given regex
 s - split the current hunk into smaller hunks
 e - manually edit the current hunk
 ? - print help

After selecting an action for the given hunk, git will show the next available hunk. In the example below, both hunks are staged with typing y.

Layer 1
Terminal Example
git add -p

diff --git a/articles_controller.rb b/articles_controller.rb
index cd678a9..ea67e94 100644
--- a/articles_controller.rb
+++ b/articles_controller.rb
@@ -1,4 +1,8 @@
 class ArticlesController < ApplicationController
+  def index
+    @articles = Article.all
+  end
+
   def show
     @article = Article.find(params[:id])
   end
(1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]? y



@@ -7,4 +11,13 @@ class ArticlesController < ApplicationController
     @article = Article.new
   end

+  def create
+    @article = Article.new(title: "...", body: "...")
+
+    if @article.save
+      redirect_to @article
+    else
+      render :new
+    end
+  end
 end
(2/2) Stage this hunk [y,n,q,a,d,K,g,/,e,?]? y


See git add to learn more about it.

Last modified on January 25, 2022.

You might also like