How to Stage a Single Line in Git
In a hurry? Watch our brief 1-minute vertical video that summarizes the info below.
Sometimes, you might have multiple unrelated changes in a single file. In such cases, you probably don't want to throw them all into the same commit; you'll want to create separate, focused commits.
This is where Git's ability to stage individual lines comes in handy!
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
Using Patch Mode to Stage Parts of a File
The magic command for this is git add with the -p (or --patch) flag.
$ git add -p index.html
This will start an interactive session where Git walks you through the "hunks" (a block of changes) in the specified file. For each hunk, Git will ask you what you want to do. You can press "?" to see a list of all available options.
Staging an Entire Hunk
If a hunk contains only changes that you want to commit, you can simply press "y" to stage the entire hunk.
Staging Specific Lines
If you only want to stage some of the lines within a hunk, you can use the "e" option. This will open the hunk in your configured code editor.
In the editor, you'll see the hunk's content. Lines that are being added have a "+" prefix, and lines that are being removed have a "-" prefix. To select which lines to stage, you simply remove the lines you don't want to stage.
For example, if you want to stage only one of three new lines, you would remove the other two lines (the ones prefixed with "+") from the editor.
After you've saved and closed the editor, Git will stage only the lines you kept.
If you run git status after this, you'll see that your file is both staged and unstaged, because it contains both staged and unstaged changes.
Tip
Staging Single Lines in Tower
In the Tower Git client, you don't have to go through the interactive command line process. You can simply select the lines you want to stage by clicking and dragging in the diff view. It's the easiest and most visual way to stage individual lines!
Learn More
- Check out the chapter on Working on Your Project in our free online book
Get our popular Git Cheat Sheet for free!
You'll find the most important commands on the front and helpful best practice tips on the back. Over 100,000 developers have downloaded it to make Git a little bit easier.
About Us
As the makers of Tower, the best Git client for Mac and Windows, we help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Ebay get the most out of Git.
Just like with Tower, our mission with this platform is to help people become better professionals.
That's why we provide our guides, videos, and cheat sheets (about version control with Git and lots of other topics) for free.