Wednesday, 14 March 2018

bash alias: using parameters inside shell command




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.


Answer



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"; }

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...