Home > Blockchain >  Programmatically retrieve the remote tracking branch of a local git branch
Programmatically retrieve the remote tracking branch of a local git branch

Time:03-11

I can view the "remote" tracking branches (ex: upstream/main) by running:

git branch -vv

As an example:

$ git branch -vv
  testing-s3           f08dcfa s3 check testing
  main                 688f70b [remote-two/main] [OS-999] Fix regional issue 17
* release-22           468f72c [upstream/release-22] adapt region against main fork
  branch-test          b490963 [origin/branch-test] Grant only explicit strings

So, for the above example, main is tracking remote-two/main ^^

I need to programmatically (one liner preferred) get the remote tracking branch of a specific branch. So, using the above example if I pass "main", the command/script would return the string remote-two/main -- how can I do this?

I was thinking something like git branch -vv | grep main | cut ...., however grep won't work since there is no guarantee the string isn't found elsewhere. Such as my above example that has the word "main" in the comments of a different branch.

CodePudding user response:

Use the --list option to select the desired branch and the --format option to customize the output to only contain the tracking information:

$ git branch --format "%(upstream:short)" --list main
remote-two/main

See the documentation for further ways of customizing the output.

  •  Tags:  
  • git
  • Related