1

Is there a way to stage or unstage (git add / git rm) files only based on what was the type of modification?

Like :

  • add/rm only files that are deleted
  • add/rm only files that are new
  • add/rm only files that are modified
  • add/rm only files that are renamed
eshirvana
  • 23,227
  • 3
  • 22
  • 38
  • I don't think git has a standard way of doing this. You may need to write some bash magic – evolutionxbox Nov 30 '21 at 23:31
  • @evolutionxbox seems like it , i couln't find anything useful in the git docs either – eshirvana Nov 30 '21 at 23:32
  • 3
    This might be helpful? [Filter git diff by type of change](https://stackoverflow.com/questions/6879501/filter-git-diff-by-type-of-change) --- use this to list the files, and then add them? – evolutionxbox Nov 30 '21 at 23:33
  • 1
    I've noticed people here don't like questions that have no code... it makes them nervous – evolutionxbox Nov 30 '21 at 23:44
  • 2
    @evolutionxbox As a general StackOverflow rule (that applies more outside the Git questions), if you haven't even attempted your own solution, you shouldn't be posting. :-) I'm not a big downvoter, especially because I tend to answer Git questions, where poor newbies are overwhelmed by Git's massive impenetrability (see https://git-man-page-generator.lokaltog.net/). – torek Dec 01 '21 at 04:30

2 Answers2

2

Based on the other linked answer you can do (in bash)

git diff --name-only --diff-filter=D | xargs git add

to e.g. only add deleted files.

You can use the other diff-filter options for modified, new, renamed files etc. And of course you can swap out git add for git reset etc.

--diff-filter=[ACDMRTUXB*]

Select only files that are

  • A Added
  • C Copied
  • D Deleted
  • M Modified
  • R Renamed
  • T have their type (mode) changed
  • U Unmerged
  • X Unknown
  • B have had their pairing Broken
  • * All-or-none

Any combination of the filter characters may be used.

Steven Fontanella
  • 764
  • 1
  • 4
  • 16
2

Steven Fontanella has given most of the answer : git diff --diff-filter will allow you to list files which are already tracked by git, or that have already been git added.

To list files that are on disk but not added yet, you will need to use git ls-files :

git ls-files --exclude-standard -o

Also, for those cases where files git detects a renaming, you will want to either process the specific output of git diff, or use the --no-renames option to list such files as a deletion + an added file.

LeGEC
  • 46,477
  • 5
  • 57
  • 104