Browse topics

git commit --amend

Version
2.51
Review
Draft

Summary#

git commit records the index as a new commit. With --amend, the new commit replaces the tip of the current branch: it keeps the same parents and records the current index as its snapshot.

Syntax#

sh
git commit -m "message"
git commit --amend
git commit --amend --no-edit
git commit --amend --reset-author --no-edit

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
  printf 'parse\n' > parser.txt
  git add parser.txt
  git commit -qm "Add parser"
  before=$(git rev-parse HEAD)

  printf 'check\n' > parser-test.txt
  git add parser-test.txt
  git commit -q --amend --no-edit

  git log --format=%s
  git ls-tree --name-only HEAD
  if [ "$before" != "$(git rev-parse HEAD)" ]; then echo "commit ID changed"; fi
  git log -1 --format='previous tip: %s' 'HEAD@{1}'
)

Expected output#

Text
Add parser
parser-test.txt
parser.txt
commit ID changed
previous tip: Add parser

Common mistakes#

Amending takes everything in the index, including unrelated changes you staged earlier, so check git diff --staged first. By default an amend keeps the author and author date. --reset-author uses the committer as author and refreshes the author date. Amending a published commit rewrites history that others may already have.

Version applicability#

Git 1.6.6 added --reset-author and Git 1.7.9 added --no-edit for amending.

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

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0