Question

So I a have a file:

...

some code here..

...

some unrelate code here..

...

and I make the following changes to it:

...

some code here that needs to be changed a bunch..

...

some unrelated code here..

...

Let's say I'm in the middle of some significant changes to the first section and I notice the typo in the later section. I want to fix the typo and commit and possibly push that right away but I'm still working on the first part and not read to share it. Obviously I could use git stash or do an intermediate commit and fix the typo in another branch but is there any way of adding only some of the changes in file to the staging area. Obviously I can unfix the typo, git add myfile then refix the typo but if the typo fix is more complex that could be kind of annoying. Is there a way to specify the lines in the file that I want to add with git add?

Was it helpful?

Solution

The -p flag will allow you to select which parts of a file you are adding. There's a popular question here which provides more details on the patch flag.

OTHER TIPS

From the terminal, git add --patch or git add --interactive can be used to selectively stage changes for commit, even within the same file.

If you'd rather use a graphical tool, git gui lets you selectively stage by right-clicking on the diff, with the "stage hunk for commit" and, if lines are selected, "stage lines for commit" commands.

Interactively staging

git add --interactive 

will allow you selective stage hunks from edited files.

Stashing changes

If you have a little foresight, you can

git stash save 'typos'
// edit file
git commit -am 'fix'

git stash pop 

The typo fixes that were temporarily 'stashed' (a.k.a.shelved in other VCSes) will be merged back into your working copy.


Vim's fugitive has far more powerful capabilities, if you are interested in using Vim for the purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top