git commit --fixup and autosquash
- Version
- 2.51
- Review
- Draft
Summary#
git commit --fixup records staged changes as a fixup! commit aimed at an earlier commit. git rebase --autosquash moves it next to its target and folds it in, keeping the target's message. The fixup adds a commit. Autosquash rewrites the rebased history, so use it before others build on those commits.
Syntax#
git commit --fixup=TARGET
git commit --fixup=amend:TARGET
git commit --fixup=reword:TARGET
git rebase -i --autosquash BASE
Example#
(
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 GIT_SEQUENCE_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"
printf 'total = a\n' > total.txt
git add total.txt
git commit -qm "Add total"
printf 'label\n' > label.txt
git add label.txt
git commit -qm "Add label"
printf 'total = a + b\n' > total.txt
git add total.txt
git commit -q --fixup=HEAD~1
git log --format=%s
git rebase -q --interactive --autosquash HEAD~3
echo "after autosquash:"
git log --format=%s
git show HEAD~1:total.txt
)
Expected output#
fixup! Add total
Add label
Add total
Start
after autosquash:
Add label
Add total
Start
total = a + b
Common mistakes#
The rebase base must be older than the target, for example the target's parent. If the target is outside the rebased range, the fixup! commit stays as a separate commit. Use amend: to fold in staged edits and replace the target message. Use reword: to replace just the message, even when changes are staged.
Version applicability#
Git 1.7.0 added interactive autosquash and Git 1.7.4 added commit --fixup. Git 2.32 added the amend: and reword: forms. Git 2.44 enabled --autosquash for non-interactive rebase; on earlier versions combine it with -i. The example sets the sequence editor to true, which accepts the generated todo list unchanged.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0