Browse topics

git branch

Version
2.51
Review
Draft

Summary#

git branch lists, creates, renames and deletes branch refs without switching to another branch. --merged lists branches whose tips are reachable from a commit, HEAD by default.

Syntax#

sh
git branch
git branch topic start-point
git branch -m old-name new-name
git branch --merged
git branch -d topic
git branch -D topic
git branch --show-current

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
  mkdir "$scratch/work"
  cd "$scratch/work"
  git init -q -b trunk
  git config user.name "Reference Example"
  git config user.email example@example.invalid
  git commit -q --allow-empty -m "Start"

  git branch topic/done
  git switch -q -c topic/wip
  git commit -q --allow-empty -m "Unfinished work"
  git switch -q trunk

  git branch -m topic/wip topic/draft
  git branch --format='%(refname:short)'
  echo "merged into HEAD:"
  git branch --format='%(refname:short)' --merged

  git branch -q -d topic/done
  if ! git branch -d topic/draft 2> /dev/null; then echo "-d refused topic/draft"; fi
  git branch -q -D topic/draft
  git branch --format='%(refname:short)'
)

Expected output#

Text
topic/done
topic/draft
trunk
merged into HEAD:
topic/done
trunk
-d refused topic/draft
trunk

Common mistakes#

-d checks the branch against its upstream when one is set, and against HEAD only otherwise, so success does not prove the work reached your current branch. -D skips the check and can leave commits that no branch refers to. --merged takes an optional commit, so an option or name placed right after it can be read as that commit.

Version applicability#

--show-current was added in Git 2.22. It prints nothing when HEAD is detached. Git 1.5.6 added --merged and Git 2.13 added --format for branch lists.

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

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0