Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in git to split up changes in a single file into two commits? [duplicate]

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?

like image 498
olleicua Avatar asked Oct 15 '13 22:10

olleicua


People also ask

What is git add P?

git add -p is basically "git add partial (or patch)" Patch mode allows you to stage parts of a changed file, instead of the entire file. This allows you to make concise, well-crafted commits that make for an easier to read history. This feature can improve the quality of the commits.

How do I edit a commit in git?

You can modify the most recent commit in the same branch by running git commit --amend. This command is convenient for adding new or updated files to the previous commit. It is also a simple way to edit or add comments to the previous commit. Use git commit --amend to modify the most recent commit.


1 Answers

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.

like image 73
ToxicFrog Avatar answered Oct 04 '22 02:10

ToxicFrog