Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous branch name

I really like git checkout - to move to my previous branch.

But sometimes I only need to know what my previous branch name is. How could I ask Git that?

For example, if git checkout - moves to branch "prev", I want the command to get just "prev".

like image 261
Julian Avatar asked Apr 09 '20 18:04

Julian


People also ask

How do I go back to previous branch?

Use the git switch - (Or git checkout - ) to switch to the previous branch you were working with. This is pretty similar to the cd - command, which is used to switch to the previous directory.

How do I find my branch name in terminal?

In order to add branch name to bash prompt we have to edit the PS1 variable(set value of PS1 in ~/. bash_profile). This git_branch function will find the branch name we are on. Once we are done with this changes we can nevigate to the git repo on the terminal and will be able to see the branch name.


Video Answer


1 Answers

git checkout - is shorthand for git checkout @{-1} (see here):

You can use the @{-N} syntax to refer to the N-th last branch/commit checked out using "git checkout" operation. You may also specify - which is synonymous to @{-1}.

You can pass this same reference to rev-parse to get the commit or branch in question:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
$ git checkout not-master
Switched to branch 'not-master'
Your branch is up to date with 'origin/not-master'.
$ git rev-parse --symbolic-full-name @{-1}
refs/heads/master
like image 142
jonrsharpe Avatar answered Nov 09 '22 21:11

jonrsharpe