DEV Community

Dzhavat Ushev
Dzhavat Ushev

Posted on • Updated on • Originally published at dzhavat.github.io

Quickly switching between branches

This post was originally posted on my blog.


It seems like my post from yesterday about getting productive with git checkout resonated with a lot of people. Some even wrote to tell me that they found the tip useful. Hopefully they will use it in their work as well.

Right now I’m sitting in the train on my way home and have a bit of time for another tiny tip. It’s something very simple and easy to do but at the same time gives me joy every time I use it. It’s how I switch between branches.

Say I’ve just switched to new-feature from master. I’ve done some work there and want to go back. They usual way to do this is:

git checkout master

Turns out, if I use - (dash) instead of the branch name, git will switch to the branch I’ve last visited. So the above becomes:

git checkout -

Running the same command again will bring me back to new-feature. Obviously, using this command will only switch between these two branches. If I want to go to a third one, I still need to write its name.

Discussion (8)

Collapse
bradtaniguchi profile image
Brad

this "back-button" command also works for changing directories:

cd - 

(I actually learned the git version 2nd by just trying it out one day hehe)

Collapse
ai7ch profile image
Aitch

recently I have come to learn this, seen it my lead-dev doing it... Maybe he doesn't know that we can also use it in git. I might gonna show off :D:D.

Collapse
michaelbrooks profile image
Michael Brooks

Ah you found this too, I posted about this a while ago and it's super helpful.

michaelbrooks.co.uk/most-helpful-g...

Collapse
dzhavat profile image
Dzhavat Ushev Author

Yes, it is. Didn‘t know that - works with other commands as well! Will definitely give it a try.

Nice post btw. We even give the same new-feature as example :D

Collapse
nikoheikkila profile image
Niko Heikkilä

As a bonus, using Fish shell you can type git checkout <TAB> to scroll through branches and pick them with Enter. This might work with ZSH as well, but I haven't tested it.

Collapse
dzhavat profile image
Dzhavat Ushev Author

Oh, that can be quite convenient. Thanks for sharing it :)

Collapse
mvoloskov profile image
Miloslav 🏳️‍🌈 🦋 Voloskov

Wow! Didn't knew that!

Collapse
adam_cyclones profile image
Adam Crockett

Love it!