Every git user is accustomed to this:
> git status
On branch master
Your branch is up-to-date with \'origin/master\'.
nothing to commit, working director
The short answer, as of Git 2.28 at least, is "no". As Brent Faust wrote, you must set the upstream of the current branch, then run git status
, then set it again and run it again, if you want git status
to print this information for multiple upstream values.
While you can't get git status
to do this, you can use a different shell command to do what you want:
counts=$(git rev-list --count --left-right $chosen_upstream...$branch)
# note: three dots
The counts
variable now contains two values: the "remote ahead, me behind" value, and the "remote behind, me ahead" value. If both values are zero, your branch and the chosen upstream are even. (If you want the counts swapped, swap the $chosen_upstream
and $branch
variables.)
To turn this into a more-useful shell function (valid in plain old sh
and bash
both):
# report: invoke as report upstream [branch]
report() {
local branch upstream count
case $# in
1) branch=$(git symbolic-ref HEAD 2>/dev/null) || return 1;;
2) branch="$2";;
*) echo "usage: report []" 1>&2; return 1;;
esac
upstream="$1"
count=$(git rev-list --count --left-right "$upstream...$branch") || return 1
set -- $count
case $1,$2 in
0,0) echo "Your branch is up-to-date with $upstream";;
0,*) echo "Your branch is $2 commits ahead of $upstream";;
*,0) echo "Your branch is $2 commits behind $upstream";;
*) echo "Your branch and $upstream have diverged,"
echo "and have $2 and $1 different commits each, respectively.";;
esac
}
(The output from the above is designed to match that from git status
, and isn't really appropriate for the two-argument form, but it shows how to do what you might want to do here.)
(answered in 2020 due to link from How do I do git status upstream?)