Home / Guides / Find Git repos that are behind their remote

Find Git repos that are behind their remote, across all your local repositories

A teammate pushes, you start work on an old copy, and the merge conflict arrives a week later. If you keep dozens of repositories on a disk, you cannot see which ones have fallen behind. This guide gives you the commands, a script that checks every repository under a folder, and the limits of any local check.

Short answer.

Run git fetch first, because Git only knows what the server had at the last fetch. Then git rev-list --left-right --count main...origin/main prints two numbers: your commits that are not on the server, and the server's commits that are not yours. The second number is how far behind you are. The script below does that for every branch of every repository under a folder.

Why "behind" needs a fetch first

Git never asks the server when you run git status. "Behind" is measured against the remote-tracking branch (for example origin/main), which is a local copy updated only by git fetch or git pull. A repository that has not fetched for a month will report "up to date" even if the server is far ahead. git fetch is safe: it downloads data and moves the remote-tracking branches, and it never changes your files or your own branches. See git fetch.

The commands, for one repository

git fetch --prune
git status -sb
git rev-list --left-right --count main...origin/main
git for-each-ref refs/heads --format="%(refname:short)  upstream=%(upstream:short)  %(upstream:track)"
  • git fetch --prune refreshes the remote data and removes remote-tracking branches that were deleted on the server.
  • git status -sb prints a first line such as ## main...origin/main [behind 2] for the current branch.
  • git rev-list --left-right --count main...origin/main prints ahead then behind. See git rev-list.
  • git for-each-ref with %(upstream:track) does it for every branch at once and prints [gone] when the branch's upstream no longer exists on the server. See git for-each-ref.

A script that checks every repository under a folder

This PowerShell script finds each repository under a root folder and prints the local branches that are behind their upstream branch or whose upstream was deleted. Add -Fetch to refresh each repository first. A repository whose fetch fails (offline, password needed, remote removed) gets its own line instead of being skipped silently. Branches that were never pushed are ignored here; that is a different question, covered in find unpushed Git commits in all your repos.

# Lists local branches that are behind their upstream (or whose upstream is gone),
# in every Git repo under a folder. -Fetch refreshes remote data first. Read-only
# apart from the fetch, which updates remote-tracking data only.
param(
    [string]$Root = 'C:\Code',
    [switch]$Fetch
)

$ErrorActionPreference = 'Continue'   # git writes progress and errors to stderr
$env:GIT_TERMINAL_PROMPT = '0'   # fail instead of waiting for a password prompt

Get-ChildItem -Path $Root -Directory -Recurse -Force -Filter .git -ErrorAction SilentlyContinue |
    ForEach-Object {
        $repo = $_.Parent.FullName
        $fetchError = $null
        if ($Fetch) {
            $out = git -C $repo fetch --quiet --prune 2>&1
            if ($LASTEXITCODE -ne 0) { $fetchError = ($out | Select-Object -First 1) }
        }
        if ($fetchError) {
            [pscustomobject]@{ Repo = $repo; Branch = ''; Behind = ''; Ahead = ''; Note = "fetch failed: $fetchError" }
        }
        foreach ($line in git -C $repo for-each-ref refs/heads --format='%(HEAD)|%(refname:short)|%(upstream:short)|%(upstream:track)') {
            $head, $name, $up, $track = $line -split '\|', 4
            if (-not $up) { continue }                       # never pushed: not this question
            $behind = if ($track -match 'behind (\d+)') { [int]$Matches[1] } else { 0 }
            $ahead  = if ($track -match 'ahead (\d+)')  { [int]$Matches[1] } else { 0 }
            $gone   = $track -match 'gone'
            if ($behind -or $gone) {
                [pscustomobject]@{
                    Repo = $repo; Branch = ($head.Trim() + ' ' + $name).Trim()
                    Behind = $behind; Ahead = $ahead
                    Note = if ($gone) { 'upstream branch deleted on the server' }
                           elseif ($ahead) { 'diverged: merge or rebase needed' } else { 'can fast-forward' }
                }
            }
        }
    } | Format-Table -AutoSize -Wrap

Save it as Find-BehindGit.ps1 and run .\Find-BehindGit.ps1 -Root D:\Code -Fetch. Point it at your code folder rather than a whole drive. The Note column tells you what to do: can fast-forward means git pull --ff-only (or, for a branch that is not checked out, git fetch origin dev:dev) brings it up to date without a merge; diverged means you have local commits too, so you merge or rebase; upstream branch deleted means the branch was merged or removed on the server and can probably be deleted locally.

What a script cannot do

  • Without -Fetch it shows the state of the last fetch. Run without it and a stale repository looks fine. That is the most common surprise.
  • Fetching many repositories is slow and can prompt. Each fetch is a network call. The script sets GIT_TERMINAL_PROMPT=0 so Git fails instead of waiting for a password, but a credential manager that shows its own window can still pop up.
  • It only knows each branch's configured upstream. A branch with no upstream is skipped, and a fork's second remote is not compared.
  • It does not pull anything. You decide what to update, which is the safe default, but it also means it does not save you the work.
  • It only runs when you run it. A scheduled task can run it, but nothing shows you the result.
  • It skips repositories where .git is a file, such as linked worktrees and submodules.

Questions

How do I check whether my local branch is behind the remote?

Run git fetch, then git status -sb. The first line shows [behind N] when the server has N commits you do not have. For a branch that is not checked out, use git rev-list --left-right --count branch...origin/branch.

Does git fetch change my files or my branches?

No. It downloads new commits and moves the remote-tracking branches such as origin/main. Your working files and your own branches stay exactly as they were until you merge, rebase or pull.

What does [gone] mean next to a branch?

The branch's upstream no longer exists on the server, usually because it was merged and deleted there. It only shows after git fetch --prune has removed the stale remote-tracking branch.

How do I update a branch that is behind without a merge commit?

If you have no local commits on it, git pull --ff-only moves it forward and refuses to do anything else. If the branch has diverged, that command stops with an error and you choose between merge and rebase.

Does GitRepoWatcher show repositories that are behind the remote?

No. It reports uncommitted changes, unpushed commits, unpublished branches and, optionally, stashes. Use the script in this guide for repositories that are behind.

Related

An unhandled error has occurred. 🗙