git add --patch

When working on a complex component or a functionality that needs to performance in multiple steps, from time to time you will find your mind playing around on its own and will lead you to be working on multiple and different tasks at the same time instead of tackling one after another, so, when you are ready to commit your work, you end up mixing different things in the same commit, which is far from ideal, and that is when it is very useful git add --patch.

According to the official git documentation this command executes git add --interactive but skips the initial command menu and goes straight forward to the patch subcommand, which means that with this command you are going to be able to interactively review the modifications done in the file and decide hunk by hunk if you want or not to add it to the stage, instead of adding directly the whole file.

How to use --patch

Executing git add <file> -p we access to the reviewer mode and then we could choose between the different options provided for handling each hunk, so we could accept all the changes or skip them, or let a hunk undecided for the moment and go ahead, for example. All the options available are:

Git shows to us the modifications grouped depending on the proximity between the lines in the file, so sometimes you have different functionalities, not related, in the same hunk just because they appear one below the other, or at least, very close, and the point is that this scenario is specifically the one we want to manage.

Preview of git add patch

For these cases, the options s and e are quite useful. s splits the hunk into smaller pieces but sometimes is not enough because the decision is not taken by us, and we need to be more accuracy and decide by ourselves, that is the case in which e option is needed. This option activates the manual edition mode. Then, we just have to follow the instructions commented below for adding or removing lines in the current hunk.

Preview of git add patch manual edition mode

In this case, if we want to add the second line but not the third, we need to delete the last one.

Finally, no matter if we mixed up different functionalities because we have a mechanism to preserve our commits lean, tidy and in order.

Preview of the repository’s commits log


Knowing in depth the tools that we use every day will let us be better professionals and be more productive, which means less hurries and more efficiency when doing a task or developing a project, so at the end, you have more life to live outside the offices. That is the reason why I think it is a good idea to getting to know these tools every day, step by step, but in depth :)

Know more

comments powered by Disqus

If you find it interesting

If you have any doubt or you want to talk about this topic, if the content or our profiles are interesting to you and you think we could something together, do not hesitate to contact us on twitter or trough the email address