git switch and restore🌸 This post has bloomed and is unlikely to change.
Git is getting easier with two new experimental commands,
git switch and
git restore, that were introduced in Git 2.23. They are basically
git checkout split up into two, one for changing branches and another for changing files. Let’s start by taking a look at how we work with branches today and how it changes with switch.
To change to an existing branch today we use
git checkout [branch-name] or if we pass the
--branch flag we can create the branch at the same time (
git checkout --branch [branch-name]).
git switch the process is very similar, to change branch we pass it the branch name:
➜ git switch another-branch Switched to branch 'another-branch'
And if we want to create a new branch and change to it, we can pass the
--create flag (or
➜ git switch -c new-feature Switched to a new branch 'new-feature'
You can find more examples and things like creating a new branch from a specific commit in the documentation.
The other thing we often use
git checkout for is restoring files to it’s “unchanged” state (resetting the working copy to how it looks in the repository).
I’ve never completely grasped the intricities of checkout for restoring files, but with
git restore it becomes much easier. To restore a file that you have changed but not yet
git added you do this:
➜ git restore file.js
If you have already run
git add and the file is in the index you can restore it by passing the
git restore --staged file.js
Finally, we can also specify where we want to restore from. By default this is the index but by passing the
--source flag we can adjust it. For example we can restore the index to a revision a couple of commits back:
git restore --source HEAD~2 --staged file.js
switch there are a lot more examples in the documentation.
restore are two new experimental commands that hopefully will make it easier to work with git from the command line.
switch for changing branches and
restore to change files.
Last update: November 10, 2019