If you’ve ever worked on a tough piece of code, you know that there is some trial and error involved. You add code, try it, tweak it, sometimes remove it altogether and then attempt to change a different part. Sometimes, at the end of a whirlwind session, do you worry you left something in that eventually didn’t need to be there?
You can use the patch option of git add to verify each and every change you’ve made to your code, so you can decide which to keep and which to throw out. Just use the -p option, like so:
mysite$ git add -p diff --git a/index.html b/index.html index 4e5050b..da78acf 100644 --- a/index.html +++ b/index.html @@ -5,5 +5,8 @@ <h1>Hello, World!</h1> + <ul> + <li><a href="about.html">About</a></li> + </ul> Stage this hunk [y,n,q,a,d,/,e,?]? y
When you’re finished, only the changes you’ve approved will be saved at your next commit. The other changes won’t be wiped out – they’ll still be in your code for you to remove as you see fit. But they won’t be “staged” for the next commit, so they won’t make it into your repository.
Another use is when you realize you made changes that should have been committed, but now you’re partway through another feature. You can commit the finished changes, while excluding the changes that are still in progress.