Git provides a powerful command called 'git add patch' that allows you to choose which changes to include in your commit selectively and interactively. In this blog post, we will explore how to use the
git add patch.
Selectively Choosing Changes
When you make changes to your code, you can use the 'git add' command to stage those changes for the next commit. However, sometimes you may have made multiple functional changes, and you only want to include some of those in your commit. This is where we can use
git add patch.
You can run
git add -p or
git add --patch to enter the interactive patch mode. In this mode, git will present you with a series of change chunks and prompt you for action.
For each change chunk, you have several options:
- 'y' - stage the change
- 'n' - do not stage the change
- 's' - split the change into smaller chunks
- 'e' - manually edit the change
- '?' - display help for the available options
By going through each change chunk and selecting the appropriate action, you can selectively choose which changes to include in your commit.
Why use it?
Ultimately, whether or not to use
git add —patchis a matter of preference, but some of the benefits are:
- It allows for a more thorough review of changes and catches unintended ones
- Streamlines the code review process
- Keeps commits focusing on one task
git add patch command gives us a powerful tool to choose which changes to include in our commits selectively. By using this command, you can separate unrelated changes, review your changes more thoroughly, and streamline the code review process.