Git branching: Reference and Examples

Git branching: Reference and Examples

Last updated:
Table of Contents

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
     - [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

Clone branch individually

Useful if you need to keep multiple branches of a single repo.

To git clone a specific branch only, use git clone -b <branch-name> <repo-url> <folder_name>:

Example: clone my-branch from into a new folder called repo-my-branch:

$ git clone -b my-branch repo-my-branch

Dialogue & Discussion