[git] Find out which remote branch a local branch is tracking

See also:
How can I see which Git branches are tracking which remote / upstream branch?

How can I find out which remote branch a local branch is tracking?

Do I need to parse git config output, or is there a command that would do this for me?

This question is related to git branch git-remote

The answer is


git branch -vv | grep 'BRANCH_NAME'

git branch -vv : This part will show all local branches along with their upstream branch .

grep 'BRANCH_NAME' : It will filter the current branch from the branch list.


Another simple way is to use

cat .git/config in a git repo

This will list details for local branches


This will show you the branch you are on:

$ git branch -vv

This will show only the current branch you are on:

$ git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)

for example:

myremote/mybranch

You can find out the URL of the remote that is used by the current branch you are on with:

$ git remote get-url $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)|cut -d/ -f1)

for example:

https://github.com/someone/somerepo.git

I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

Having tried all of the solutions here, I realized none of them were good in all situations:

  • works on local branches
  • works on detached branches
  • works under CI

This command gets all names:

git branch -a --contains HEAD --list --format='%(refname:short)'

For my application, I had to filter out the HEAD & master refs, prefer remote refs, and strip off the word 'origin/'. and then if that wasn't found, use the first non HEAD ref that didn't have a / or a ( in it.


I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

I think git branch -av only tells you what branches you have and which commit they're at, leaving you to infer which remote branches the local branches are tracking.

git remote show origin explicitly tells you which branches are tracking which remote branches. Here's example output from a repository with a single commit and a remote branch called abranch:

$ git branch -av
* abranch                d875bf4 initial commit
  master                 d875bf4 initial commit
  remotes/origin/HEAD    -> origin/master
  remotes/origin/abranch d875bf4 initial commit
  remotes/origin/master  d875bf4 initial commit

versus

$ git remote show origin
* remote origin
  Fetch URL: /home/ageorge/tmp/d/../exrepo/
  Push  URL: /home/ageorge/tmp/d/../exrepo/
  HEAD branch (remote HEAD is ambiguous, may be one of the following):
    abranch
    master
  Remote branches:
    abranch tracked
    master  tracked
  Local branches configured for 'git pull':
    abranch merges with remote abranch
    master  merges with remote master
  Local refs configured for 'git push':
    abranch pushes to abranch (up to date)
    master  pushes to master  (up to date)

I use this alias

git config --global alias.track '!sh -c "
if [ \$# -eq 2 ]
 then
   echo \"Setting tracking for branch \" \$1 \" -> \" \$2;
   git branch --set-upstream \$1 \$2;
 else
   git for-each-ref --format=\"local: %(refname:short) <--sync--> remote: %(upstream:short)\" refs/heads && echo --URLs && git remote -v;
fi  
" -'

then

git track

note that the script can also be used to setup tracking.

More great aliases at https://github.com/orefalo/bash-profiles


git branch -vv | grep 'BRANCH_NAME'

git branch -vv : This part will show all local branches along with their upstream branch .

grep 'BRANCH_NAME' : It will filter the current branch from the branch list.


Following command will remote origin current fork is referring to

git remote -v

For adding a remote path,

git remote add origin path_name


git branch -r -vv

will list all branches including remote.


If you are using Gradle,

def gitHash = new ByteArrayOutputStream()
    project.exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = gitHash
    }

def gitBranch = new ByteArrayOutputStream()
    project.exec {
        def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d'  -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
        commandLine "bash", "-c", "${gitCmd}"
        standardOutput = gitBranch
    }

Following command will remote origin current fork is referring to

git remote -v

For adding a remote path,

git remote add origin path_name


Two choices:

% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline

or

% git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
origin/mainline

Update: Well, it's been several years since I posted this! For my specific purpose of comparing HEAD to upstream, I now use @{u}, which is a shortcut that refers to the HEAD of the upstream tracking branch. (See https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem ).

Original answer: I've run across this problem as well. I often use multiple remotes in a single repository, and it's easy to forget which one your current branch is tracking against. And sometimes it's handy to know that, such as when you want to look at your local commits via git log remotename/branchname..HEAD.

All this stuff is stored in git config variables, but you don't have to parse the git config output. If you invoke git config followed by the name of a variable, it will just print the value of that variable, no parsing required. With that in mind, here are some commands to get info about your current branch's tracking setup:

LOCAL_BRANCH=`git name-rev --name-only HEAD`
TRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`
TRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`
REMOTE_URL=`git config remote.$TRACKING_REMOTE.url`

In my case, since I'm only interested in finding out the name of my current remote, I do this:

git config branch.`git name-rev --name-only HEAD`.remote

I don't know if this counts as parsing the output of git config, but this will determine the URL of the remote that master is tracking:

$ git config remote.$(git config branch.master.remote).url

git-status porcelain (machine-readable) v2 output looks like this:

$ git status -b --porcelain=v2
# branch.oid d0de00da833720abb1cefe7356493d773140b460
# branch.head the-branch-name
# branch.upstream gitlab/the-branch-name
# branch.ab +2 -2

And to get the branch upstream only:

$ git status -b --porcelain=v2 | grep -m 1 "^# branch.upstream " | cut -d " " -f 3-
gitlab/the-branch-name

If the branch has no upstream, the above command will produce an empty output (or fail with set -o pipefail).


Another method (thanks osse), if you just want to know whether or not it exists:

if git rev-parse @{u} > /dev/null 2>&1
then
  printf "has an upstream\n"
else
  printf "has no upstream\n"
fi

Yet another way

git status -b --porcelain

This will give you

## BRANCH(...REMOTE)
modified and untracked files

Lists both local and remote branches:

$ git branch -ra

Output:

  feature/feature1
  feature/feature2
  hotfix/hotfix1
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/master

$ git remote --verbose 

(or)

$ git remote --v 

(or)

$ git remote -vv

(or) To Know about the remote branch in details and Head branch

$ git remote show origin

To Know about the specific, remote branch and Head branch

$ git remote show origin | grep master
Username for 'https://github.com': Pra.....@9
  HEAD branch: master
    master tracked
    master merges with remote master
    master pushes to master (up to date)

Two choices:

% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline

or

% git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
origin/mainline

I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

Here is a command that gives you all tracking branches (configured for 'pull'), see:

$ git branch -vv
  main   aaf02f0 [main/master: ahead 25] Some other commit
* master add0a03 [jdsumsion/master] Some commit

You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column.

If you need info on both 'pull' and 'push' configuration per branch, see the other answer on git remote show origin.


Update

Starting in git version 1.8.5 you can show the upstream branch with git status and git status -sb


You can use git checkout, i.e. "check out the current branch". This is a no-op with a side-effects to show the tracking information, if exists, for the current branch.

$ git checkout 
Your branch is up-to-date with 'origin/master'.

The local branches and their remotes.

git branch -vv 

All branches and tracking remotes.

git branch -a -vv

See where the local branches are explicitly configured for push and pull.

git remote show {remote_name}

If you are using Gradle,

def gitHash = new ByteArrayOutputStream()
    project.exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = gitHash
    }

def gitBranch = new ByteArrayOutputStream()
    project.exec {
        def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d'  -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
        commandLine "bash", "-c", "${gitCmd}"
        standardOutput = gitBranch
    }

The local branches and their remotes.

git branch -vv 

All branches and tracking remotes.

git branch -a -vv

See where the local branches are explicitly configured for push and pull.

git remote show {remote_name}

I think git branch -av only tells you what branches you have and which commit they're at, leaving you to infer which remote branches the local branches are tracking.

git remote show origin explicitly tells you which branches are tracking which remote branches. Here's example output from a repository with a single commit and a remote branch called abranch:

$ git branch -av
* abranch                d875bf4 initial commit
  master                 d875bf4 initial commit
  remotes/origin/HEAD    -> origin/master
  remotes/origin/abranch d875bf4 initial commit
  remotes/origin/master  d875bf4 initial commit

versus

$ git remote show origin
* remote origin
  Fetch URL: /home/ageorge/tmp/d/../exrepo/
  Push  URL: /home/ageorge/tmp/d/../exrepo/
  HEAD branch (remote HEAD is ambiguous, may be one of the following):
    abranch
    master
  Remote branches:
    abranch tracked
    master  tracked
  Local branches configured for 'git pull':
    abranch merges with remote abranch
    master  merges with remote master
  Local refs configured for 'git push':
    abranch pushes to abranch (up to date)
    master  pushes to master  (up to date)

If you want to find the upstream for any branch (as opposed to just the one you are on), here is a slight modification to @cdunn2001's answer:

git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream}

That will give you the remote branch name for the local branch named YOUR_LOCAL_BRANCH_NAME.


Improving on this answer, I came up with these .gitconfig aliases:

branch-name = "symbolic-ref --short HEAD"
branch-remote-fetch = !"branch=$(git branch-name) && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name) && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"
branch-url-fetch = !"remote=$(git branch-remote-fetch) && git remote get-url        \"$remote\" #"  # cognizant of insteadOf
branch-url-push  = !"remote=$(git branch-remote-push ) && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf

git branch -r -vv

will list all branches including remote.


Another simple way is to use

cat .git/config in a git repo

This will list details for local branches


Another method (thanks osse), if you just want to know whether or not it exists:

if git rev-parse @{u} > /dev/null 2>&1
then
  printf "has an upstream\n"
else
  printf "has no upstream\n"
fi

You can use git checkout, i.e. "check out the current branch". This is a no-op with a side-effects to show the tracking information, if exists, for the current branch.

$ git checkout 
Your branch is up-to-date with 'origin/master'.

git-status porcelain (machine-readable) v2 output looks like this:

$ git status -b --porcelain=v2
# branch.oid d0de00da833720abb1cefe7356493d773140b460
# branch.head the-branch-name
# branch.upstream gitlab/the-branch-name
# branch.ab +2 -2

And to get the branch upstream only:

$ git status -b --porcelain=v2 | grep -m 1 "^# branch.upstream " | cut -d " " -f 3-
gitlab/the-branch-name

If the branch has no upstream, the above command will produce an empty output (or fail with set -o pipefail).


Lists both local and remote branches:

$ git branch -ra

Output:

  feature/feature1
  feature/feature2
  hotfix/hotfix1
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/master

You can try this :

git remote show origin | grep "branch_name"

branch_name needs to be replaced with your branch


If you want to find the upstream for any branch (as opposed to just the one you are on), here is a slight modification to @cdunn2001's answer:

git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream}

That will give you the remote branch name for the local branch named YOUR_LOCAL_BRANCH_NAME.


Here is a command that gives you all tracking branches (configured for 'pull'), see:

$ git branch -vv
  main   aaf02f0 [main/master: ahead 25] Some other commit
* master add0a03 [jdsumsion/master] Some commit

You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column.

If you need info on both 'pull' and 'push' configuration per branch, see the other answer on git remote show origin.


Update

Starting in git version 1.8.5 you can show the upstream branch with git status and git status -sb


Improving on this answer, I came up with these .gitconfig aliases:

branch-name = "symbolic-ref --short HEAD"
branch-remote-fetch = !"branch=$(git branch-name) && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name) && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"
branch-url-fetch = !"remote=$(git branch-remote-fetch) && git remote get-url        \"$remote\" #"  # cognizant of insteadOf
branch-url-push  = !"remote=$(git branch-remote-push ) && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf

Yet another way

git status -b --porcelain

This will give you

## BRANCH(...REMOTE)
modified and untracked files

I use this alias

git config --global alias.track '!sh -c "
if [ \$# -eq 2 ]
 then
   echo \"Setting tracking for branch \" \$1 \" -> \" \$2;
   git branch --set-upstream \$1 \$2;
 else
   git for-each-ref --format=\"local: %(refname:short) <--sync--> remote: %(upstream:short)\" refs/heads && echo --URLs && git remote -v;
fi  
" -'

then

git track

note that the script can also be used to setup tracking.

More great aliases at https://github.com/orefalo/bash-profiles


I don't know if this counts as parsing the output of git config, but this will determine the URL of the remote that master is tracking:

$ git config remote.$(git config branch.master.remote).url

$ git remote --verbose 

(or)

$ git remote --v 

(or)

$ git remote -vv

(or) To Know about the remote branch in details and Head branch

$ git remote show origin

To Know about the specific, remote branch and Head branch

$ git remote show origin | grep master
Username for 'https://github.com': Pra.....@9
  HEAD branch: master
    master tracked
    master merges with remote master
    master pushes to master (up to date)

Update: Well, it's been several years since I posted this! For my specific purpose of comparing HEAD to upstream, I now use @{u}, which is a shortcut that refers to the HEAD of the upstream tracking branch. (See https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem ).

Original answer: I've run across this problem as well. I often use multiple remotes in a single repository, and it's easy to forget which one your current branch is tracking against. And sometimes it's handy to know that, such as when you want to look at your local commits via git log remotename/branchname..HEAD.

All this stuff is stored in git config variables, but you don't have to parse the git config output. If you invoke git config followed by the name of a variable, it will just print the value of that variable, no parsing required. With that in mind, here are some commands to get info about your current branch's tracking setup:

LOCAL_BRANCH=`git name-rev --name-only HEAD`
TRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`
TRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`
REMOTE_URL=`git config remote.$TRACKING_REMOTE.url`

In my case, since I'm only interested in finding out the name of my current remote, I do this:

git config branch.`git name-rev --name-only HEAD`.remote

This will show you the branch you are on:

$ git branch -vv

This will show only the current branch you are on:

$ git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)

for example:

myremote/mybranch

You can find out the URL of the remote that is used by the current branch you are on with:

$ git remote get-url $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)|cut -d/ -f1)

for example:

https://github.com/someone/somerepo.git

I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

Having tried all of the solutions here, I realized none of them were good in all situations:

  • works on local branches
  • works on detached branches
  • works under CI

This command gets all names:

git branch -a --contains HEAD --list --format='%(refname:short)'

For my application, I had to filter out the HEAD & master refs, prefer remote refs, and strip off the word 'origin/'. and then if that wasn't found, use the first non HEAD ref that didn't have a / or a ( in it.


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to branch

Get git branch name in Jenkins Pipeline/Jenkinsfile Why do I have to "git push --set-upstream origin <branch>"? Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.? When does Git refresh the list of remote branches? Fix GitLab error: "you are not allowed to push code to protected branches on this project"? Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository." Git: Merge a Remote branch locally git pull from master into the development branch Depend on a branch or tag using a git URL in a package.json? How can I copy the content of a branch to a new local branch?

Examples related to git-remote

Why does Git tell me "No such remote 'origin'" when I try to push to origin? Git - What is the difference between push.default "matching" and "simple" error: src refspec master does not match any How to connect to a remote Git repository? Changing the Git remote 'push to' default What does '--set-upstream' do? Git: How to remove remote origin from Git repo Git push error: "origin does not appear to be a git repository" How to add a local repo and treat it as a remote repo Git branching: master vs. origin/master vs. remotes/origin/master