When working with Git from the command line, it's useful to know whether your current branch is up to date with the remote and whether a specific branch exists locally. Here’s how to do both efficiently from your terminal.

Check if the current branch has changes to pull

To see if your local branch is behind the remote (i.e., if there are commits to pull), run:

git fetch
git status

This updates your remote tracking information and will display something like:

Your branch is behind 'origin/main' by 2 commits, and can be fast-forwarded.

That means you can safely pull the latest changes using:

git pull

If you want a scriptable version, use the following command to see how many commits you are behind:

git rev-list --count HEAD..origin/main

If the output is greater than 0, your local branch is behind and there are changes to pull.

To compare both directions (behind and ahead):

git rev-list --left-right --count origin/main...HEAD

Example output:

2    1

This means:

  • You're 2 commits behind origin/main (you should pull).
  • You're 1 commit ahead of origin/main (you should push).

Check if a branch exists locally

If you want to check whether a specific branch exists in your local repository, use:

git branch --list <branch-name>

Example:

git branch --list feature/login

If the branch exists, its name will be printed. If it doesn’t, the output will be empty.

To perform this check in a shell script or conditionally in your terminal:

if git rev-parse --verify --quiet feature/login; then
  echo "Branch exists"
else
  echo "Branch does not exist"
fi

This is a clean way to verify branch existence without cluttering your output with error messages.

Summary

Task Command
Fetch changes git fetch
Check for commits to pull git rev-list --count HEAD..origin/main
Compare local/remote changes git rev-list --left-right --count origin/main...HEAD
Check if branch exists locally git branch --list <branch>
Scriptable check for branch git rev-parse --verify --quiet <branch>