2

My sub-directory has multiple .git repo. To Find them I am using:

$ echo **/.git        
demo-component-a/.git demo-component-b/.git

Now I actually need the parent directories. demo-component-a & demo-component-b.

I found this neat feature to find the parent of a path:

$ var=/home/blueray/Documents/antora/demo-component-b
$ echo $var:h
/home/blueray/Documents/antora

Now I am trying to combine these two.

I have tried the following:

$ echo $(echo **/.git):h 
demo-component-a/.git demo-component-b/.git:h

This is not what I want. What can be done here?

3
**/.git(:h)

The h history modifier strips the filename component off of each pathname. To use a history modifier on the result of a wildcard expansion, put it in a glob qualifier: in parentheses at the end, with a leading : to indicate that it's a history modifier.

To only find directories, which would exclude git linked working trees, use (/:h) as the glob qualifier.

As you found out, that :h history modifier can also be applied on parameter expansions (like in csh where that feature comes from). In zsh, you can also apply it to each word resulting of the $IFS splitting of a command substitution, by writing it:

print -rC1 -- ${$(echo **/.git):h}

The above would be wrong for other reasons though (like usage of echo, splitting file paths on SPC+TAB+NL+NULL). To be equivalent to **/*.git(:h), that would rather be:

print -rC1 -- ${(0)"$(print -rNC1 -- **/*.git)"}
| improve this answer | |
  • It takes 10 min to accept an answer. Sorry for the delay. – blueray Jun 5 at 9:11
  • @blueray Well, it's good to give others a chance to come up with a better solution... :-) – Kusalananda Jun 5 at 9:13
  • By the way, if I need to run git commit -am "Latest Commit" in all these directories, how can I do that? – blueray Jun 5 at 9:18
  • @blueray for dir in **/.git(/:h); do git -C $dir commit ...; done But you don't need the :h for that I think. – Kusalananda Jun 5 at 9:20
  • Why would you use (/:h) here? It would exclude git worktrees, where .git is a regular file rather than a directory, and I don't see any reason to exclude worktress here. – Gilles 'SO- stop being evil' Jun 5 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.