Git | git checkout to Switch branch
Git checkout is mostly used for switching from one branch to another. It is also used to check out files and commits.
Switch to a branch
This command is used to switching one branch to another in your local.
Before switching branch:
- Ensure that the current branch must be committed or stashed
- Ensure that the branch exists in your local to switch
git checkout <branch name>
git checkout new_branch
This command switch to the branch last checked out
git checkout -
Create a new branch and switch to it
This command creates a new branch in your local (-b stands for the branch) and switches to it.
git checkout -b <branch name>
git checkout -b new_branch
Clone a remote branch and switch to it
This command creates a new branch in your local and switches to it along with copy the latest updates from the remote.
git checkout -b <branch name> origin/<branch name>
git checkout -b new_branch origin/new_branch
Discard changes to a file
This command discards the changes done to the file.
git checkout -- <file-name.txt>
git checkout -- new_file.txt