Search code examples
gitgit-aliasposh-git

Using variables in git alias


I'm trying to create an alias for checking out the master branch and merging the branch I was on before switching. Right now, my alias looks like this: med = "!f() { git checkout master; git merge ${1}; git branch -d ${1}; }; f"

It means that every time I want to use it, I have to call it using the current branch's name: git med topic. What I want is avoid it, calling git med without arguments.

I know that I can get the current branch's name like this: git rev-parse --abbrev-ref HEAD, but after I have switched to master, I can no longer use it. So, I need to save it in a variable before switching to master.

How do I work with variables in git alias?

I'm on Windows, using posh-git.


Solution

  • This is a combination of my comment and @torek 's:

    med = "!f() {BRANCH=`git symbolic-ref --short HEAD`; git checkout master; git merge $BRANCH; git branch -d $BRANCH; }; f"
    

    which seems to work. (And bails out early, rather than late, if you're in a detached HEAD state)