1

I want to make an alias for a somehow complex git command:

git push origin HEAD:refs/for/BRANCH-NAME

I want the command my-alias my-branch to run git push origin HEAD:refs/for/my-branch. So far I've tried:

alias my-push='git push origin HEAD:refs/for/$1'
alias my-push='git push origin HEAD:refs/for/"$1"'

I would like to know the right solution and the explanation why does above fail.


I do have such alias:

alias run-schema='cd ~/sources/schema; python -m SimpleHTTPServer $1'

and it works fine - there are no extra apostrophe/quote signs.

ducin
  • 25,621
  • 41
  • 157
  • 256
  • The solution @fredtantini points to is the one I would do. – Karl Dec 01 '14 at 13:24
  • @fredtantini this is not a duplicate. I found the link above at first, but couldn't find out what is wrong with my try. – ducin Dec 01 '14 at 13:28
  • As I said bellow _You can't have any parameter for an alias (by design)_ – Gilles Quénot Dec 01 '14 at 13:28
  • ORLY? I think I can. Look at the example I added to my description (python SimpleHTTPServer). – ducin Dec 01 '14 at 13:30
  • It doesn't work for the reason you think it does. `run-schema foo` expands to `cd ...; python -m SimpleHTTPServer $1 run-schema`. Since the interactive shell doesn't have any positional parameters set, the unquoted `$1` disappears, leaving `run-schema` as the only positional argument for the `python` command. Try running something like `set -- nonexistantschema`, then try your alias. – chepner Dec 01 '14 at 14:02

2 Answers2

3

Aliases do text replacement. When you say

alias foo='echo $1'

and call

foo baz

this is replaced by

echo $1 baz

$1 expands to nothing, and you get, in effect, echo baz. This is also the way your second alias works -- or doesn't work -- since the $1 is at the end, when it expands to nothing, it appears as though it had been replaced with what comes after it. There are funny ways to play around with this. For example, if you say

alias foo='echo $1'
bar() { foo; }
bar qux

this will execute echo qux.

The solution to your problem is, as has been mentioned, a function:

my_push() { git push origin "HEAD:refs/for/$1"; }
Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Ok, now I see how it all works. And, most importantly, I know why. Thank you for the explanation. – ducin Dec 01 '14 at 13:41
1

What I would do using a function:

my-push(){ git push origin HEAD:refs/for/"$1"; }

You can't have any parameter for an alias (by design), you need a shell function like I does here. Moreover, when you put single quotes around some variables, the variables will be never evaluated.

chepner
  • 497,756
  • 71
  • 530
  • 681
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Would you mind removing the word *some* and provide information when it actually happens? With your description I don't know precisely what's wrong. – ducin Dec 01 '14 at 13:26
  • Single quotes prevent expansion of *all* variables. – tripleee Dec 01 '14 at 13:59