Switch to previous checked out git branch

I jump between git branches pretty regularly, doing so from the command-line pretty exclusively. When I need to switch to another branch, I’ve always just checked it out. I even have a nice little alias, gco to save from needing to type out git checkout.

Don’t really remember what I was researching at the time, but in my travels I found out about the git switch command. The command accepts a final argument that could be a branch name, or a dash.

Similar to how cd can accept a - and jump to the previous directory, the switch command can do the same for branches:

% git switch -
Zsh

Doing so takes you back to the previous branch you were on.

The bigger thing that I learned is that git checkout can ALSO accept the dash and check out the previously checked out branch:

% git checkout -

# with a cool alias
% gco -
Zsh

Doing it this way allows me to not disrupt my existing workflow and muscle memory.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.