4

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.

ulu
  • 5,872
  • 4
  • 42
  • 51
  • 2
    Have you tried `med = "!f() {BRANCH=\`git rev-parse --abbrev-ref HEAD\`; git checkout master; git merge $BRANCH; git branch -d $BRANCH; }; f"` – Creynders May 11 '16 at 09:03
  • 3
    For some reason `git rev-parse --abbrev-ref HEAD` is commonly quoted as the way to get the current branch name, but this is subtly wrong: it produces the literal string `HEAD`, which is *not* a branch name, when you are not on a branch at all. For a case like this, use `git symbolic-ref --short HEAD` and check exit status (it will fail with a `fatal: ...` message when HEAD is detached). In any case @Creynders is right: just invoke the shell. (You could use `git check-ref-format --branch @{-1}` but it does not handle detached HEAD cases correctly either.) – torek May 11 '16 at 09:34
  • @Creynders thanks! It worked for me. I'm just not experienced at all in shell scripts. Please make this a separate entry so that I could mark it as the answer. – ulu May 12 '16 at 14:19

2 Answers2

6

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)

Creynders
  • 4,573
  • 20
  • 21
  • 1
    I had to put a space between `{` and `BRANCH=` for this to work for me (i.e. `!f() { BRANCH=...`). I'm using windows and running the command through the terminal in jetbrains rider IDE. – Tim Jun 23 '21 at 16:48
  • ```med = "!BRANCH=`git symbolic-ref --short HEAD`; git checkout develop; git pull; git merge $BRANCH; git checkout $BRANCH "``` worked just fine for me. – Ben Bailey Apr 21 '22 at 14:53
  • This didn't work for me, see my answer: https://stackoverflow.com/questions/37157669/using-variables-in-git-alias/74978712#answer-74978712 – s6mike Jan 02 '23 at 03:02
0

I found in bash (debian) that wrapping the alias in double quotes didn't work.

I had to use single quotes:

'!f() { BRANCH=`git symbolic-ref --short HEAD`; git checkout master; git merge $BRANCH; git branch -d $BRANCH; }; f'`
s6mike
  • 497
  • 5
  • 16