8

Is there a way to quickly detect if there are any untracked files?

I can list all of the untracked files with

git ls-files --other --directory --exclude-standard

But this is slow if there are many untracked files. Is there something like git diff -q where the exit status determines whether or not any untracked files exist?

Community
  • 1
  • 1
k107
  • 13,813
  • 7
  • 55
  • 56

2 Answers2

21

If you have what you want when you've seen the first untracked file, quit right then.

If you're on GNU/anything

git ls-files --other --directory --exclude-standard | sed q1

will set rc1 if there are any

Otherwise,

anyuntracked() {
    return `git ls-files -o --directory --exclude-standard | sed q | wc -l`
}
anyuntracked

will do the same job

jthill
  • 42,819
  • 4
  • 65
  • 113
  • To get results more in line with `git status`, add `--no-empty-directory`. – pjvandehaar Oct 19 '15 at 20:56
  • I don't think this works at all. If you benchmark this command it's exactly the same speed with and without sed. I suspect that git is not flushing the output until all of it is available. – user3467349 Oct 24 '15 at 08:10
  • @user3467349 I don't think the few dozen filenames it takes to fill a buffer add enough time to bother many people, he said "many", but if you've got some weird layout that scatters few untracked files across many directories or something there's always the `stdbuf` command to force linebuffering on the ls-files stdout. – jthill Nov 08 '15 at 19:16
  • `-d` will return the list of deleted files; it's not a synonym for `--directory` – tavnab Mar 13 '18 at 14:03
  • @tavnab Thanks! Fixed. – jthill Mar 13 '18 at 15:13
3

git status will notify you of any untracked files.

Example output:

remco@Prosperpine ~/code/Sick-Beard (master) $ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   init.osx
nothing added to commit but untracked files present (use "git add" to track)
Rem.co
  • 3,785
  • 3
  • 25
  • 37
  • 1
    I think `git ls-files` is still faster than `git status` – k107 Jun 13 '12 at 19:11
  • 1
    Yes, as a matter for fact you are right! I timed both commands on a test set of 100000 new files. `git status` took `real:0m0.927s`, while `ls-files` only took `real:0m0.468s`. (Not much of an answer, but perhaps good to know) – Rem.co Jun 13 '12 at 19:28