开发者

git re-add only those files that have already been staged

I often have a situation where I have git added a set of files for a commit, but then have to make a modification to those files so end up with the modifications on those same files in Changed but not updated.

Is there a one liner I can execute to git add only the files that exist in Changed but not updated and Changes to be committed lists?

markdsievers$git status
# On branch master
#
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   src/com/foo/Bar.java
#   modified:   src/com/foo/Foo.java
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be c开发者_运维百科ommitted)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   src/com/foo/Bar.java
#   modified:   src/com/foo/Foo.java
#   modified:   src/com/foobar/FooBar.java

For the above example I only want Foo.java and Bar.java but not FooBar.java added to the Changes to be committed: list.


This is one way:

 git add -u $(git status --porcelain | grep ^MM | cut -d ' ' -f 2)


The accepted answer won't work if filenames contain a space. Also -u is useless is this case, but will add all unstaged files if there are no files that are both in Changed but not updated and Changes to be committed list. Use this instead:

git add $(git status -z | perl -0ne 'print $1 if $_ =~ /^MM(.*)$/')

This will only work for files that are changed only. If you want this to work for files that are deleted, added, renamed or copied as well, use this:

git add $(git status -z | perl -0ne 'print $1 if $_ =~ /^[MADRC][MD](.*)$/')

But be careful with last one. For example, if the file is added in index, but its deletion is unstaged, running this command will delete the file in index as well, causing you to lose contents of that file.

Note that both will work only from root directory of your git repo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜