Commit Only Part of a File’s Changes in Git

Better Stack Team
Updated on June 24, 2024

To commit only part of a file's changes in Git, you can use the git add -p or git add --patch command, which allows you to interactively select portions of the file to stage for the next commit. Here's how you can do it:

Step 1: Stage Partial Changes

 
git add -p <file>

Replace <file> with the path to the file you want to stage partial changes from.

Step 2: Interactively Select Changes

After running the command, Git will display a prompt showing the hunks of changes within the file. You'll have several options for each hunk, such as:

  • y: Stage this hunk for the next commit.
  • n: Do not stage this hunk.
  • s: Split this hunk into smaller hunks.
  • e: Manually edit this hunk.
  • q: Quit the interactive mode.

Choose the appropriate option for each hunk to select the changes you want to include in the next commit.

Step 3: Commit Staged Changes

After selecting the desired changes, you can commit the staged changes as usual:

 
git commit -m "Your commit message"

This will commit only the changes that you staged using git add -p.

Note:

  • git add -p allows you to selectively stage changes within a file, making it useful for committing only specific parts of a file while leaving the rest unchanged.
  • This method is helpful when you've made changes to multiple sections of a file and only want to commit a subset of those changes.
  • After staging the changes, you can review them using git diff --cached to ensure that you're committing the correct changes.
Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github