Git somewhat recently introduced two new commands, switch and restore

Git somewhat recently introduced two new commands, switch and restore. Together, these commands split up the functionality of the git checkout
command.
The old waySection titled: The old way
At first glance it might seem odd that these new commands aren’t introducing any new functionality. But consider all the different types of things that the checkout
command can do:
# Switch to an existing branchgit checkout <branch>
# Create a new branch (and switch to it)git checkout -b newBranch
# Discard changes to a filegit checkout -- <file>
# Replace the contents of a file (with whatever's in main)git checkout main -- <file>
There are two categories of functionality happening in those examples:
- The first two commands switch which branch you’re on (
git switch
) - The second two commands replace the contents of files in your working directory (
git restore
)
The new waySection titled: The new way
Here’s how you would perform those same tasks using switch and restore:
# Switch to an existing branchgit switch <branch>
# Create a new branch (and switch to it)# -c is short for --creategit switch --create newBranch
# Discard changes to a filegit restore <file>
# Replace the contents of a file (with whatever's in main)git restore <file> --source main
Bonus TipSection titled: Bonus Tip
The restore
command also provides a (potentially more logical) new way to unstage files.
# The old waygit reset HEAD <file>
# The new waygit restore --staged <file>
The old way used the reset
command to copy from HEAD (your last commit) to the index (staging area). Because the HEAD and index now match, the change you made to the file only exists in your working directory, meaning the file is “unstaged”.
With the new way, you’re stating that you want to “restore staged files” and by default, if --staged
is given, the contents are restored from HEAD. The effect is the same as the old way, copying from HEAD to the index, “unstaging” the file.
I’ve always felt that the old way was a roundabout way to accomplish unstaging a file, made extra confusing by the implied --mixed
. The new way is still not the most clear thing in the world, but in my opinion it’s in incremental improvement.
To clear that up, you should create a git alias!
git config --global alias.unstage "restore --staged"
And then you can use it like this:
git unstage <file>