Git switch and restore
If you’ve been using Git for a while you’re probably used to the ubiquitous git checkout command, which is somewhat overloaded in what it’s doing. You can use checkout to switch branches, create branches, update the working tree to a past commit, wiping working tree changes, and a few more things. Put simply, this command has too many responsibilities, and should be refactored.
This is what happened in Git 2.23.0: We can now use two other, more specialized commands, git switch and git restore.
git switch is used to managed branches, that is creating a branch or switching to a branch. It is complementary with git branch, which lists, deletes, and (also) creates branches.
You use git switch as follows:
01 02 03 04 05 06 07 08 09 10 11 | # switches to master branchgit switch master# switches to branch feature-123git switch feature-123# switches to last branch, here mastergit switch -# creates a new branch feature-234git switch -c feature-234 |
git restore is used to restore working tree files, in the same way you would have used git checkout to checkout or restore a certain working tree state. Here are some examples for git restore:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | echo "modified" >> file.txt# restores all files in the current directorygit restore .# working tree cleanecho "modified" >> file.txtgit add file.txtgit restore .# no changes# restores staged changes from the indexgit restore --staged .# working tree modifiedgit restore .# working tree clean# checks out a single file from a previous commitgit restore -s a0b1c2d file.txt |
For more information have a look at the documentation of switch and restore, or by executing git help <command>.
This post has been reposted from my newsletter issue 041.
Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Git switch and restore Opinions expressed by Java Code Geeks contributors are their own. |



