Browse topics

git reset

Version
2.51
Review
Draft

Summary#

git reset with a commit moves the current branch there. --soft leaves the index and working tree alone, --mixed, the default, also resets the index, and --hard resets the index and the working tree. Git saves the previous tip in ORIG_HEAD.

Syntax#

sh
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
git reset -- path/to/file

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 'v1\n' > app.txt
  git add app.txt
  git commit -qm "Version 1"
  printf 'v2\n' > app.txt
  git commit -qam "Version 2"

  for mode in soft mixed hard; do
    git reset -q "--$mode" HEAD~1
    printf '%s: status [%s] file %s\n' "$mode" "$(git status --short)" "$(cat app.txt)"
    # Return to the second version before trying the next mode.
    git reset -q --hard 'HEAD@{1}'
  done
)

Expected output#

Text
soft: status [M  app.txt] file v2
mixed: status [ M app.txt] file v2
hard: status [] file v1

Common mistakes#

--hard discards uncommitted changes to tracked files and can delete untracked files that are in the way of the target. The reflog tracks commits, not uncommitted edits, so it cannot bring those back. Run git status first. All three modes can move the branch off commits others already use. Given paths instead of a branch move, reset updates only their index entries.

Version applicability#

The three modes shown here are available on the Git 2.51 version line.

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

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0