Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readGit

Use git switch and restore instead of checkout

Use git switch to change branches and git restore to recover or unstage files, even when a branch and file share a name.

You edited a file called notes, changed your mind, and ran git checkout notes to throw the edit away. Git did not touch the file. A branch called notes also exists, so git moved you to it and carried your edit along.

$ git status --short
 M notes
$ git checkout notes
Switched to branch 'notes'
M	notes

git checkout does two jobs. Given a branch name it moves you there, and given a path it restores that file from the index. When one name matches both, the branch wins and your edit stays.

Move with switch

git switch changes branches. Switch back to main to try this sequence after the checkout example.

$ git switch -c feature
Switched to a new branch 'feature'
$ git switch main
Switched to branch 'main'
M	notes
$ git switch -
Switched to branch 'feature'
M	notes

-c creates the branch and moves you onto it. A bare - goes back to the branch you were on before, so the last command returned me to feature.

Undo with restore

git restore works on paths. Switch back to main, then use restore to discard the unstaged edit and copy notes from the index:

$ git switch main
Switched to branch 'main'
M	notes
$ git restore notes
$ git status --short
$ git branch --show-current
main
$ cat notes
one

With a clean index, the status is empty, notes is back to its committed one, and I am still on main, even though the branch notes exists. Pass a branch name that is not a file and it stops: git restore only-branch prints error: pathspec 'only-branch' did not match any file(s) known to git.

If feature has a commit that changes notes to two, git restore --source feature notes copies that version into your working tree. Your branch and index stay where they are, so git status --short shows M notes on main.

Unstage with restore

With that edit in the working tree, run git add notes. Now git status --short shows M notes with the letter in the left column. git restore --staged notes moves the change out of the index.

The status then shows M notes, the letter in the right column. The edit is still in the file. To discard it as well, run git restore notes once more.

If you need to keep the edit, stop after git restore --staged notes.