checkout, reset -> switch, restore#
In Git 2.23, the overloaded git checkout command was split into git switch (for branch management) and git restore (for file management) to make intentions clearer.
While git checkout is now fully replaced by these two commands, git reset is only partially replaced for its file-level operations (like unstaging). git reset remains the primary tool for moving the branch pointer (HEAD) to a different commit.
Command Migration#
| Action / Situation | as-is (git checkout / git reset) | to-be (git switch / git restore) | Notes |
|---|---|---|---|
| Switch branch | git checkout <branch> | git switch <branch> | Dedicated to switching branches |
| Create and switch branch | git checkout -b <new-branch> | git switch -c <new-branch> | Only the option name changed |
| Switch to a commit | git checkout <commit> | git switch --detach <commit> | Explicitly states detached HEAD |
Discard WD changes (ST -> WD) | git checkout -- <file> | git restore <file> | Restores the working directory |
Unstage a file (LR -> ST) | git reset HEAD <file> | git restore --staged <file> | Dedicated to staging area manipulation |
restore vs reset vs revert#
While these commands can be used to undo changes, they operate on different levels.
git restore#
Focuses on restoring files to a certain state without moving the branch pointer (file-centric).
- Restore a file from a specific commit (
LR -> WD):$ git restore --source=<commit> <file>
git reset#
Focuses on moving the HEAD and optionally updating the index and working directory (commit-centric).
- Undo the latest commit: Move
HEADto the state before the current commit.$ git reset HEAD^ - Scope:
git reset <ref>is specifically forHEAD(and the current branch). To move a general branch to a new commit without checking it out, usegit branch -f <branch> <ref>. - Flags:
--soft: MovesHEADonly. Index and working directory are preserved.--mixed(default): MovesHEADand resets the index. Working directory is preserved.--hard: MovesHEAD, resets the index, and resets the working directory. Danger: uncommitted changes are lost.
git revert#
Focuses on undoing the changes of a specific commit by creating a new commit (history-centric).
- Undo the latest commit: Apply the inverse changes of the current commit as a new commit.
$ git revert HEAD - Use Case: Preferred for public repositories because it doesn’t rewrite history.