Git add only all new files, not modified files

10,290

Solution 1

Maybe

git add $(git ls-files -o --exclude-standard)

git ls-files lets you list the files managed by git, filtered by some options. -o in this case filters it to only show "others (i.e. untracked files)"

The $(...) statement passes the return value of that command as an argument to git add.

Solution 2

You can use short mode of git status (see man git-status(1)), which gives the following output:

Without short mode:

$ git status

...


# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   README
#   application/libraries/Membres_exception.php
no changes added to commit (use "git add" and/or "git commit -a")

With short mode:

$ git status -s
 M application/models/membre_model.php
?? README
?? application/libraries/Membres_exception.php

Then using grep, awk and xarg, you can add the files where the first column is ??.

$ git status -s | grep '??' | awk '{ print $2 }' | xargs git add 

and see that it worked:

$ git status
# On branch new
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   README
#   new file:   application/libraries/Membres_exception.php
Share:
10,290
Andreas Fliesberg
Author by

Andreas Fliesberg

@antte

Updated on June 13, 2022

Comments

  • Andreas Fliesberg
    Andreas Fliesberg almost 2 years

    Is there a way to only add new files and not add modified files with git? That is, files that are listed as untracked with git status.

    Other than ofcourse adding each file separately.

    It's not absolutely necessary to do this in my case, the real question for me is answered here: How to make git-diff and git log ignore new and deleted files?

    That is, don't show diff on new files, so I'm asking this more because i couldn't find an answer to it anywhere.

  • Michael Wild
    Michael Wild about 11 years
    You'll need to exclude the ignored files again, otherwise git add will complain. E.g. by using the --exclude-standard flag to the git ls-files -o call.
  • Nils Werner
    Nils Werner about 11 years
    OK, didnt know that. Thanks!
  • Michael Wild
    Michael Wild about 11 years
    If I remember correctly, it only complains, telling you that it will ignore those files and that if you want to really add them, you'll have to use the --force flag. Still, annoying.
  • Bruno Gelb
    Bruno Gelb almost 9 years
    good idea, though there's a problem: in case where filepath contains spaces awk '{ print $2 }' will grab only first part of such filepath.
  • Bruno Gelb
    Bruno Gelb almost 9 years
    how about this one: git status -s | grep '??' | awk '{print substr($0, index($0, $2))}' | xargs git add
  • PJ Brunet
    PJ Brunet over 4 years
    Works but it will add untracked files.