Git : How to get name of the branch tracked by the current one?

212 Views Asked by At

In order to write a specific script, I need to check is the current branch has a tracked remote and what is the name of this remote. Is there a way to get only the name of the branch tacked by the current one, without having to parse git remote show origin output?

2

There are 2 best solutions below

0
On

This should work:

git rev-parse --symbolic-full-name @{u}
1
On

Since 28fb8438 (Introduce @{upstream} notation, 2009-09-10) included in Git 1.7+, you can use the HEAD@{upstream} (or HEAD@{u} for short) to achieve this.

For educational purposes, here's a shell script equivalent.

#!/bin/sh

cbranch=`git rev-parse --abbrev-ref HEAD`
cmerge=`git config branch.$cbranch.merge`
cremote=`git config branch.$cbranch.remote`
if [ $? -eq 0 ]; then
    echo "$cremote/`git rev-parse --abbrev-ref $cmerge`"
else
    return 1
fi