Home > database >  How to set a default value for command line parameter for git alias?
How to set a default value for command line parameter for git alias?

Time:11-23

I am trying to add an alias in .gitconfig which should resolve to a default value if there is not a command line argument.

lgs = "!f() { git log --stat $1; }; f" 

git lgs should print the stat logs for the last commit. git lgs -2 - should print the stat logs for the last 2 commit. ( This one is working ).

I have tried a few options but no result

  • lgs = "!f() { git log --stat $1:=-1; }; f"
  • lgs = "!f() { git log --stat $1:-1; }; f"
  • lgs = "!f() { git log --stat $1=-1; }; f"

How can I implement it correctly ?

CodePudding user response:

You want ${1--1} here, I think.

Explanation

Git aliases are run by a POSIX-style shell (sh). POSIX shell has:

${variable-default}

and:

${variable:-default}

as expansion options, where if $variable is not set, you get the default instead. The :- variant, which looks a bit like one of those old-style emoticons, means "use the default if the variable is set but expands to the empty string".

In most cases we use variable names here, e.g.:

somevar=somevalue

or:

anothervar=$(git ls-files --stage -- file.ext)

for instance, and then we'd have ${somevar-default}. But $1 is the first positional parameter, $2 is the second, and so on, and these work in these positions as well.

The default you want in this case is -1 so ${1--1}, which admittedly looks funny, works.

Note that Vogel612's comment was very close, as these shells do also have:

${variable=default}

and:

${variable:=default}

which behave similarly (expanding to the default if the variable is unset, and in the second case if the variable is set to the empty string as well) but also have the side effect of setting the variable. This is particularly useful when used with the no-op : (colon) command:

f() {
    local name="$1" email="$2"
    : ${name:="default name"} ${email:="<[email protected]>"}
    # now you can refer to "$name" and "$email";
    # they are set and non-empty, even if someone passed the
    # empty string as arguments 1 and/or 2.
}

(Unfortunately the local construct, while very widely available and generally a good idea, is not in POSIX sh. I was surprised to discover this recently. It keeps the variable from "escaping" the scope of the function. Fortunately, for one-off functions in Git aliases, it's not needed.)

  • Related