Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why `git add -p` doesn't stage untracked files?

Tags:

git

I've created a new file foo.rb.

$ git add -p foo.rb

$ No changes.

However, adding without -p works. Is this a bug or a feature? I would expect it to let me stage parts of the file.

like image 935
dimid Avatar asked Nov 18 '25 18:11

dimid


2 Answers

git add --patch is documented like this:

This effectively runs add --interactive, but bypasses the initial command menu and directly jumps to the patch subcommand.

And git add --interactive is described to only add modified changes:

Add modified contents in the working tree interactively to the index.

So no, this behavior is by design.

Adding new files using patch doesn’t make much sense anyway, since the whole file addition is a single hunk which can either be staged or not (or you have to edit the patch manually). So it’s either git add foo.rb or not.

You can hover add an empty file using git add --intent-to-add file or git add -N file in short. This stages an empty file with that file name, so the next time you run git add -p, the file is already known and a real patch is provided.

like image 138
poke Avatar answered Nov 20 '25 14:11

poke


-p or --patch compares the staging area with your working tree and gives you the possibility to stage only portions of a file compared to the full file itself. This interactive command is especially helpful if you want to split your changes of a file into seperated commits, rather than one big one. However, if your file is untracked this makes no sense, since it is not part of your working tree yet. Therefore there will be no changes. add is a multifunctional command. If you use git add one time before the file is part of the working tree and it will work as expected.

After using git add, running git add -p will actually show you the diff and give you several options to work with.

Stage this hunk [y,n,q,a,d,/,e,?]?

A little extract from the man page for those options.

  • y – stage this hunk
  • n – do not stage this hunk
like image 42
oshell Avatar answered Nov 20 '25 14:11

oshell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!