Git Checkout and Switch
To start working on a branch, you must move to it. Git has two commands for it: the newer git switch (Git 2.23 and later) and the older git checkout. Both work, but switch is simpler, because it does only one job.
Syntax
git switch <branch>
git switch -c <new-branch>
git checkout <branch>
git checkout -b <new-branch>
Switch to another branch
$ git switch develop
Switched to branch 'develop'
$ git branch
* develop
main
Create a branch and switch to it
$ git switch -c feature-search
Switched to a new branch 'feature-search'
$ echo "search" > search.html
$ git add .
$ git commit -q -m "Add search page"
$ git log –oneline
2d479bc (HEAD -> feature-search) Add search page
52a1595 (main, develop) Add home page
The old way is git checkout -b feature-search. It does the same.
Go back to the previous branch
$ git switch main
Switched to branch 'main'
$ git switch –
Switched to branch 'feature-search'
The dash (-) means the branch where you were before.
Files change when you switch
When you switch a branch, Git changes the files in your folder to match that branch. Look at the file search.html:
$ ls
index.html
search.html
$ git switch main
Switched to branch 'main'
$ ls
index.html
Switch with uncommitted changes
If you have changes which do not conflict with the other branch, they come with you. If they conflict, Git stops you.
$ echo "changed on main" > index.html
$ git switch feature-search
Switched to branch 'feature-search'
M index.html
Nothing conflicts here, so Git moves. If the same file was different on the other branch, you would see an error like “Your local changes would be overwritten”. Then commit or stash your changes first.
Detached HEAD
Normally HEAD points to a branch. If you check out a commit directly (not a branch), you are in a “detached HEAD” state. You can look around and even commit, but those commits do not belong to any branch, and can be lost.
First we put away our edit with git stash (explained in the Git Stash chapter), and then we open the previous commit.
$ git stash -q
$ git switch –detach HEAD~1
HEAD is now at 52a1595 Add home page
To keep work done in this state, create a branch from there with git switch -c new-branch. To leave without keeping anything, switch to a branch with git switch main.
checkout can also restore files
The old git checkout did many things: switch branches, create branches and restore files. This was confusing, so Git split the job: switch for branches and restore for files. See Git Restore.
| Task | Old way | New way |
|---|---|---|
| Switch branch | git checkout main | git switch main |
| Create and switch | git checkout -b new | git switch -c new |
| Restore a file | git checkout -- file | git restore file |
| Open an old commit | git checkout a3f9c1e | git switch --detach a3f9c1e |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |