5

Is there a command to permit checkout the last branch? Like:

git checkout --recent

or

git checkout --previous

The idea is when you switch branch too often you it's easy to forget the branch you were working before the current one. Also if there's a way to set a alias for this that would be valide.

Igor Medeiros
  • 4,026
  • 2
  • 26
  • 32
  • `git help reflog` to see how to examine the history of commits/branches you have been on; `git help rev-parse` for the various syntaxes (syntaxen?) for specifying what you want to check out... – twalberg Apr 17 '14 at 16:20
  • 1
    Does this answer your question? [Is there any way to git checkout previous branch?](https://stackoverflow.com/questions/7206801/is-there-any-way-to-git-checkout-previous-branch) – ian.pvd Jul 16 '20 at 18:26
  • yes, it's the same idea of the selected answer here – Igor Medeiros Jul 16 '20 at 22:23

1 Answers1

8

What you're looking for is -

git checkout -

For example, say you're on branch foo, and there exists a branch bar.

* foo
bar

Check out bar

> git checkout bar

foo
* bar

Going back to foo

> git checkout -

* foo
bar

The - "shortcut" also works for the cd and ls commands from within a bash terminal.

Bucket
  • 7,415
  • 9
  • 35
  • 45
  • 3
    I didn't know you could do this but I tried it and it works, +1 – Tim Apr 17 '14 at 14:05
  • I believe this works in most bash shells. I've used `cd -` many times to go back to the directory I just came from. Saves a *ton* of hefty keystrokes. – Bucket Apr 17 '14 at 14:07
  • @DesertIvy, so this is a system functionality or something provided by git? Would be nice to learn how this works too. – Igor Medeiros Apr 17 '14 at 14:08
  • 2
    @Medeiros git may have implemented it this way to match the already existing functionality in the 'regular' bash shell – Tim Apr 17 '14 at 14:11
  • They way I understand it, it's a standard bash parameter that is used to indicate "last directory," and git-bash extended this to mean "last branch." It could have a more broad, overarching meaning that I'm missing, but that's my understanding of it. [This post](http://stackoverflow.com/a/8045499/464188) explains some of its other uses and quirks. – Bucket Apr 17 '14 at 14:12
  • The question is, does this work in every system or is this system dependent? – Igor Medeiros Apr 17 '14 at 14:28
  • 1
    I'm pretty sure it's platform-independent. I've used this command in bash shells on my Windows work computer, my old *nix boxes, and my current Mac at home. You won't have any luck running it in a native Windows Command Prompt, so it sounds like for the most part it's bash-only. – Bucket Apr 17 '14 at 14:41