patronus
patronus

Reputation: 103

Passing string in positional parameter for Git alias

I am trying to create a git alias that takes a string as a entire positional paramter.

For e.g. I have a alias as follows:

my-alias = "!f() { \
     param1 = $1; \
     param2 = $2; \
     rem_param = ${@:3};\
     };f"

And I want to use alias as:

$ git my-alias abc "this is one parameter" 11 22 44

Here my parameters should be

param1 = abc
param2 = "this is one parameter"
rem_pram = 11 22 44

The way I have setup it starts treating every word in the string as a separate parameter. So the question is there any way to treat the string as one parameter?

Upvotes: 2

Views: 594

Answers (1)

bk2204
bk2204

Reputation: 76459

When you start a Git alias with !, that tells Git to invoke the shell for your alias. By default, the shell expands words with whitespace, and so your assignment to param2 consists of only "this". To solve this, you need to double-quote your arguments. Since you already have double quotes here, you need to escape them. Furthermore, to have syntactically valid assignments, you also need to remove the spaces around the equals sign.

So things would look like this:

my-alias = "!f() { \
    param1=\"$1\"; \
    param2=\"$2\"; \
    rem_param=\"${@:3}\"; \
};f"

I should also point out that because Git always uses /bin/sh as the shell for aliases (unless it was compiled explicitly for a different one) the ${@:3} syntax will only work on systems that use bash as /bin/sh. This alias fails on most Debian and Ubuntu systems, where /bin/sh is dash.

Upvotes: 4

Related Questions