Git branching: Reference and Examples
Last updated:Table of Contents
- Checkout file from branch
- Checkout file from commit
- Delete branch locally and on remote
- Make local branch track remote branch
- Fetch and track remote branch
- Git clone branch
Checkout file from branch
$ git checkout <branch-name> -- path/to/file.txt
Checkout file from commit
$ git checkout <commit-hash> -- path/to/file.txt
Delete branch locally and on remote
use
-D
instead of-d
to force-delete an unmerged branch
Use git branch -d <branch_name>
to delete it locally and then use git push <remote_name> --delete <branch_name>
to delete it remotely:
1) Delete the branch locally
$ git branch -d old-branch Deleted branch old-branch (was eeb9376).
2) Delete the branch on remote
$ git push origin --delete old-branch To git@github.com:username/my-repo.git - [deleted] old-branch
Make local branch track remote branch
Use git branch -u <remote-name> <local-name>
EXAMPLE: make local branch foo
track origin/foo
$ git branch -u origin/foo foo
Fetch and track remote branch
TEMPLATE: git fetch origin my-branch:my-branch
then git checkout my-branch
1) fetch
$ git fetch origin branch-1:branch-1
2) checkout
$ git checkout branch-1
Git clone branch
This is useful if you need to keep multiple branches of a single repo.
To git clone a branch, use git clone -b <branch-name> <url>
:
$ git clone -b my-branch git@github.com:my-user/repo.git repo-my-branch