Software Development

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 branch
git switch master
 
# switches to branch feature-123
git switch feature-123
 
# switches to last branch, here master
git switch -
 
# creates a new branch feature-234
git 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 directory
git restore .
# working tree clean
 
echo "modified" >> file.txt
git add file.txt
git restore .
# no changes
# restores staged changes from the index
git restore --staged .
# working tree modified
git restore .
# working tree clean
 
# checks out a single file from a previous commit
git 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.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button