0

I have a git repo of configuration files segregated by branches, e.g.:

refs/heads/branch1, file - settings.properties
refs/heads/branch2, file - settings.properties

etc.

I'm trying to grep certain property of every each of the settings.properties file in every each of the repository:

git for-each-ref refs/heads --shell --format=‘%(refname:short)’ | xargs -n1 git checkout | cat settings.properties | grep ‘host.name’

The first command gives me the list of my branches, the second one checks me out to every branch one after another and I expect 3rd command cat the file and 4th to grep certain property. First 2 commands work just fine but if I run the whole thing it just greps host.name only for the first branch.

I'm obviously missing something essential about the pipelines. I know I can write it as a shell script and do all this in a loop, but I would like to keep the 'pipeline' approach, because I may often need to cat different files and grep different properties and wouldn't want to deal with passing parameters into the script

maxi
  • 369
  • 5
  • 14
  • You didn't wrap `cat` in a loop or with `xargs`, so it will only run once, where was you want it to run for each ref. – root Nov 28 '19 at 23:01

1 Answers1

2

You don't need to check out each branch to get the information about that file. You can instead use git cat-file to show the contents of the file on that branch instead.

So you could do something a little like this (untested):

git for-each-ref refs/heads --shell --format='%(refname:short)' | \
    xargs -n1 -I{} git cat-file blob {}:settings.properties | grep 'host.name'

Or if you wanted it to be even shorter, you could just use git grep directly:

git for-each-ref refs/heads --shell --format='%(refname:short)' | \
    xargs -n1 -I{} git --no-pager grep host.name {}:settings.properties
bk2204
  • 64,793
  • 6
  • 84
  • 100
  • The second command did it but in an interactive way (I have to press 'q' every time to iterate over all the branches). The first one gives me usages of git cat file, I'm assuming because git cat-file wants an object's hash. If I'm trying to add git object-hash to the pipeline it doesn't switch the branches. Any ideas? Much appreciate your help! – maxi Nov 29 '19 at 04:16
  • 1
    I've edited it to use `git cat-file blob`, which should be the correct invocation. You can use any arbitrary blob expression there. If you don't want the pager, you can prefix the `git grep` with `env GIT_PAGER=cat`, which will disable the pager. – bk2204 Nov 29 '19 at 04:47
  • 1
    `git --no-pager …` – phd Nov 29 '19 at 09:39
  • @bk2204 both options works, thank you very much, really appreciate it! – maxi Nov 29 '19 at 14:48