Browse topics

git fetch and git pull

Version
2.51
Review
Draft

Summary#

git fetch downloads objects and updates remote-tracking refs such as origin/main without moving your current branch. git pull fetches and then integrates: --ff-only refuses divergent history, while --rebase replays local commits. With the usual branch refspec, fetch --prune drops remote-tracking refs for branches deleted on the remote.

Syntax#

sh
git fetch origin
git fetch --prune origin
git log HEAD..origin/main
git pull --ff-only
git pull --rebase

Example#

sh
(
  set -eu
  scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
  trap 'rm -rf -- "$scratch"' EXIT
  unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
  export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
  export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
  export GIT_PAGER=cat GIT_EDITOR=true
  export GIT_AUTHOR_NAME="Reference Example" GIT_AUTHOR_EMAIL=example@example.invalid
  export GIT_COMMITTER_NAME="Reference Example" GIT_COMMITTER_EMAIL=example@example.invalid

  git init -q -b trunk "$scratch/author"
  git -C "$scratch/author" commit -q --allow-empty -m "Start"
  git clone -q "$scratch/author" "$scratch/reader"
  git -C "$scratch/author" commit -q --allow-empty -m "Publish update"

  cd "$scratch/reader"
  git fetch -q origin
  echo "local: $(git log -1 --format=%s)"
  echo "tracking: $(git log -1 --format=%s origin/trunk)"
  echo "behind by: $(git rev-list --count HEAD..origin/trunk)"

  git pull -q --ff-only
  echo "local after pull: $(git log -1 --format=%s)"

  git commit -q --allow-empty -m "Local note"
  git -C "$scratch/author" commit -q --allow-empty -m "Second update"
  if ! git pull -q --ff-only 2> /dev/null; then echo "--ff-only refused divergence"; fi
  git pull -q --rebase
  git log --format=%s
)

Expected output#

Text
local: Start
tracking: Publish update
behind by: 1
local after pull: Publish update
--ff-only refused divergence
Local note
Second update
Publish update
Start

Common mistakes#

Fetching alone leaves your local branch and files unchanged, and comparisons with origin/main are only as current as the last fetch. When both sides have new commits, state how to combine them with --rebase, --no-rebase or --ff-only to make the choice explicit. Pulling with rebase can rewrite local commits that other people already use. Pruning works on the configured refspec, so a refspec that maps remote tags directly to local tags can also delete local tags.

Version applicability#

Git 1.5.4 added pull --rebase. Git 1.6.6 added pull --ff-only and fetch --prune. Git 2.27 began warning when git pull had no configured way to reconcile branches. The Git 2.51 manual describes fast-forward only as the default when you choose no method.

The complete example requires Git 2.28 or later for git init -b.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0