Close

Git - Creating and switching branches using 'branch' and 'checkout' commands

[Updated: Mar 20, 2019, Created: Mar 19, 2019]

By default our changes in Git are committed to the 'master' branch.

We can create a separate branch (say XYZ) and diverge from the 'master' or current branch where changes can be committed to XYZ without messing with the current line of development.

Creating new branch

git branch <branch_name>

Switching to other branch

git checkout <branch_name>

Create and switching to new branch

git checkout -b <branch_name>

Listing all branches

git branch

Example

Let's start git bash for windows, create a git project and commit a file:

joe@jpc MINGW64 /d
$ mkdir git-example

joe@jpc MINGW64 /d
$ cd git-example/

joe@jpc MINGW64 /d/git-example
$ git init
Initialized empty Git repository in D:/git-example/.git/

joe@jpc MINGW64 /d/git-example (master)
$ echo a > test.txt

joe@jpc MINGW64 /d/git-example (master)
$ git add -A && git commit -m "adding file"
[master (root-commit) e6bdbbf] adding file
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

joe@jpc MINGW64 /d/git-example (master)
$ git status
On branch master
nothing to commit, working tree clean

joe@jpc MINGW64 /d/git-example (master)
$ git branch
* master

As seen in the last command output ('git branch') we have only 'master' branch so far. Also notice the * character that prefixes the master branch: it indicates the branch that we currently have checked out.

Let's create a new branch (XYZ), switch to it and make changes to our file 'test.txt':

joe@jpc MINGW64 /d/git-example (master)
$ git branch XYZ

joe@jpc MINGW64 /d/git-example (master)
$ git branch
  XYZ
* master

joe@jpc MINGW64 /d/git-example (master)
$ git checkout XYZ
Switched to branch 'XYZ'

joe@jpc MINGW64 /d/git-example (XYZ)
$ git branch
* XYZ
  master

joe@jpc MINGW64 /d/git-example (XYZ)
$ echo b >> test.txt

joe@jpc MINGW64 /d/git-example (XYZ)
$ git add -A && git commit -m "new changes"
[XYZ b48c793] new changes
 1 file changed, 1 insertion(+)

joe@jpc MINGW64 /d/git-example (XYZ)
$ git status
On branch XYZ
nothing to commit, working tree clean

joe@jpc MINGW64 /d/git-example (XYZ)
$ cat test.txt
a
b

Let's switch back to 'master' and see the content of 'test.txt' file:

joe@jpc MINGW64 /d/git-example (XYZ)
$ git checkout master
Switched to branch 'master'

joe@jpc MINGW64 /d/git-example (master)
$ cat test.txt
a

As seen above the changes made in branch XYZ are not available in 'master' branch.

When we switch branches, Git resets our working directory to look like it did the last time we committed on that branch. It adds, removes, and modifies files automatically to make sure our working copy is what the branch looked like on our last commit to it.

Command to list all branches with last commits

git branch -v

In our above example:

joe@jpc MINGW64 /d/git-example (master)
$ git branch -v
  XYZ    b48c793 new changes
* master e6bdbbf adding file

See Also