0

When I git switch foo I would like to know if I need to rebase it onto master. Is there any way to make git switch foo check if foo is behind master and print a message like

Current branch foo is up to date.

or

Current branch foo is 6 commits behind `master`

after it has switched? Ideally I run the exact same command - git switch (so it doesn't mess up my muscle memory when working on different systems) and it only runs when I actually do git switch - anything that runs on every prompt will be too slow.

Timmmm
  • 88,195
  • 71
  • 364
  • 509

2 Answers2

2

Yes you can. First you can use the post-checkout commit to run after git switch:

touch .git/hooks/post-checkout
chmod +x .git/hooks/post-checkout

And then in that file you can use this code to print a useful message:

#!/bin/bash

set -e

git rev-list --left-right --count master...HEAD | awk '{print "Behind "$1" - Ahead "$2""}'

(Credit for that last command)

Example output:

git switch -
Updating files: 100% (1459/1459), done.
Switched to branch 'fix_warning_message'
Behind 0 - Ahead 2
Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • 1
    Note that when Git switches branch names, it automatically does this for whatever the new branch's *upstream* is. But usually you want the upstream of branch `xyz` to be `origin/xyz`, not `master`, so having the post-checkout hook do this separately for `master` is probably the way to go. You might want to augment your post-checkout hook though: sometimes you're not actually switching anything, just extracting some file(s), and post-checkout gets a flag argument for that. – torek Mar 28 '22 at 20:25
1

You can always use Git status command.

In my personal opinion, Git status is one of the best git command that will tell you about ahead/behind count for the current branch.

Its usage is simple,

$ git status

If you want to learn more about Git commands, you can find a list of git commands here on one page - https://acompiler.com/git-commands/

Rajeev Bera
  • 2,021
  • 1
  • 16
  • 30
  • The point was to do it automatically. Also `git status` is quite slow on large repos because it has to walk all the files. – Timmmm Mar 28 '22 at 14:29