Introduction

We are all used to using git checkout when dealing with different branches in our project. But what is the purpose of git switch and git restore? In this blog post, I will show what they both are along with examples of how to use them.

git switch

git switch is used to switch to a specific branch. Both the index and working tree are then updated in order to be matched to the new branch. Any new commit that is made will be added to the tip of the newly created branch.

git switch dev             # Equivalent to git checkout dev
git switch -c dev          # Equivalent to git checkout -b dev
git switch -c dev HEAD~5   # Branch off at HEAD~5
git switch --detach HEAD~5 # Checkout commit at HEAD~5 without any branching

git restore

git restore allows the restoration of files in the working tree along “with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source."[1]

restore options:

  • --source - Choose the files to copy
  • --staged, --worktree - Choose the destination of the files in --source.

Examples

git restore --source HEAD~5 main.js # No need to use --worktree as it is implicit

Let’s say main.js was deleted rm -f main.js, we can use restore as follows: git restore main.js

Restore all files with the js extension: git restore '*.js'

Restore a file from HEAD: git restore --staged user.js # Equivalent to git reset

Conclusion

git switch and git restore are very useful when dealing with different aspects when working on projects. Hopefully, this short post helped clarify what they are and what they do.

[1] https://git-scm.com/docs/git-restore