W3docs

How to Checkout the Previous Branch in Git

This tutorial provides an easy way of checking out the previous branch. Find a shortcut to the command line to save your time and an experimental solution.

As time is precious, the command line shortcuts are always warmly welcomed by programmers. Git suggests an easy way of switching between the current branch and the previous ones. Here, we are going to discuss how to do that.

Checkout the previous branch

The simplest way of switching to the previous branch is using the git checkout command:

git checkout

git checkout -
Info

git checkout - is equivalent to git checkout @{-1}

The <kbd class="highlighted">git checkout</kbd> command is similar to <kbd class="highlighted">the cd -</kbd> command in Linux, which switches the current directory to the previous one.

The <kbd class="highlighted">git checkout</kbd> command allows not only switching to the previous branch, but also getting back to the N-th last branch/commit.

Here is how you can do that:

git checkout

git checkout @{-N}

You can also git merge the previous branch into the current one by running the following command:

git merge

git merge -
Info

Use git merge - when you want to integrate changes from the previous branch into your current branch. Use git checkout - or git switch - when you just want to navigate back to it.

Warning

Git 2.23 introduced the git switch command, which is now stable and recommended for branch navigation. Note that git checkout for switching branches is deprecated in modern Git workflows in favor of git switch.

git switch

git switch -

The <kbd class="highlighted">git switch</kbd> command switches to a specific branch. The working tree and the staging area are updated to match the branch, and all new git commits will be added to the tip of that branch.

The git checkout Command

It is a very common thing to move back and forth between two branches. Git has simplified programmers' work, and now there is no need to write the branch name each time. This happens due to the <kbd class="highlighted">git checkout</kbd> command, which switches branches or restores working tree files. It allows switching between several features in just a single Git Repository. In modern Git, git switch is preferred for branch navigation, while git checkout is primarily used for restoring files.