14

Using git list-files gives me the directories and the files tracked within. Is there a command like:

git list-directories

or something similar that lists only the tracked non-empty non-recursive directory names?

tmaric
  • 4,835
  • 3
  • 33
  • 65
  • 2
    Probably not. Git tracks files, not directories. You might be able to somehow derive that information from the `list-files` command though and define a git alias that does what you want. – Ajedi32 Nov 27 '13 at 16:12
  • @Ajedi32 Thanks, then I'll do that. – tmaric Nov 27 '13 at 16:13
  • Cool. Once you figure it out be sure to post an answer here for the benefit of anyone else who might have the same question in the future. – Ajedi32 Nov 27 '13 at 16:16

2 Answers2

17

I think this will give you what you want:

git ls-files | xargs -n 1 dirname | uniq

So, take the output of git ls-files and pipe that into dirname, then uniq the results. This appears to work locally for me.

CDub
  • 12,780
  • 4
  • 47
  • 65
  • I'd do a sed, `...|sed s,/[^/]*$,,|uniq`, avoiding `xargs -n 1` seems like a good rule of thumb to me. – jthill Nov 27 '13 at 16:30
  • 1
    @CDub : This gives out the subdirectories as well. Still useful though. – tmaric Nov 27 '13 at 16:31
  • 1
    Why wouldn't you want subdirectories? – CDub Nov 27 '13 at 16:32
  • 1
    @CDub: I'm tracking directories that define simulation test cases. There are a lot of subdirectories. When the parameters I'm using to set up the tests differ strongly in numbers and values, I create another test and start tracking it with git, I don't have it defined as another version of the same directory in that case. Once the algorithm is up and running I need to decide which tests to keep, so I need to do some cleaning up: so I only want to list the top level directories to see if I am tracking all of them, or which ones are not tracked. – tmaric Nov 27 '13 at 16:57
  • I believe that this misses directories that have no files, just other directories. Here is a method that considers them as well: https://stackoverflow.com/a/54162211/895245 – Ciro Santilli新疆棉花TRUMP BAN BAD Jan 12 '19 at 17:39
  • this won't work if file names contain newlines. See [Why *not* parse `ls` (and what to do instead)?](https://unix.stackexchange.com/q/128985/44425) – phuclv Jun 11 '20 at 07:35
1
git ls-tree -rt HEAD:./ | awk '{if ($2 == "tree") print $4;}'

If the files may contain spaces, we would have to play around with: Using awk to print all columns from the nth to the last which is not very fun.

-r makes it recurse, and -t makes it print trees when recursing, which is turned off by default.

I was unable to use ls-tree as mentioned at: https://stackoverflow.com/a/20247815/895245 because it is hard to deal with directories that have no files, just other directories.

This method also shows empty trees.

Tested on Git 2.19.0.