little cubes

New git commands to replace 'checkout'

Zach Olivare - 2022 Feb 16

Git somewhat recently introduced two new commands, switch and restore

New git commands to replace 'checkout'

Git somewhat recently introduced two new commands, switch and restore. Together, these commands split up the functionality of the git checkout command.

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:

1 2 3 4 5 6 7 8 9 10 11 # Switch to an existing branch git checkout <branch> # Create a new branch (and switch to it) git checkout -b newBranch # Discard changes to a file git 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 way

Here's how you would perform those same tasks using switch and restore:

1 2 3 4 5 6 7 8 9 10 11 12 # Switch to an existing branch git switch <branch> # Create a new branch (and switch to it) # -c is short for --create git switch --create newBranch # Discard changes to a file git restore <file> # Replace the contents of a file (with whatever's in main) git restore <file> --source main

Bonus Tip

The restore command also provides a (potentially more logical) new way to unstage files.

1 2 3 4 5 # The old way git reset HEAD <file> # The new way git 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>