0

I'd like to create a git alias that does stuff on a different branch than HEAD is on, and then switches back to the original branch. But I'm not sure if there's any way to remember the old branch. I tried using a tag:

git tag placeholder &&
  git co master &&
  git co placeholder &&
  git tag -d placeholder

But this leaves me with a detached HEAD, rather than on the original branch.

Simon Lepkin
  • 1,021
  • 1
  • 13
  • 25

2 Answers2

2

You could wrap your intended work something like this:

[alias]
        bookmark = "!export OLD_HEAD=`git rev-parse --abbrev-ref HEAD`; git checkout develop; <do stuff>; git checkout $OLD_HEAD"

Essentially this saves the current branch to an environment variable, does the intended work, and checks out the original branch.

acanby
  • 2,936
  • 24
  • 26
  • According to the docs, `git rev-parse --abbrev-ref ` should return a "non-ambiguous short name of the objects name". But it seems to me that "HEAD" is similarly non-ambiguous, and short. Why, then, is the name of the branch returned? – Simon Lepkin Feb 03 '15 at 20:36
  • 1
    HEAD is a reference to a real object. Essentially the command follows the link that HEAD holds and gets the real object, in this case the branch you are on. See http://stackoverflow.com/questions/2304087/what-is-head-in-git for more info. – acanby Feb 03 '15 at 22:13
1

You can use git checkout - (that is, just a dash at the end) to go back to the last branch you had checked out (like how cd - works).

mipadi
  • 398,885
  • 90
  • 523
  • 479