git advanced alias parameter issues

376 views Asked by At

Suppose I have this in my .gitconfig alias:

testing =!"\
echo \"hi\" \
"

if I run git testing 1 4 it will echo the parameters back to me:

hi 1 4


Also if I use sh to try to get all the parameters it doesn't show the first:

testing =!sh -c 'echo "$@"'

if I run git testing 1 4 it will only show 4.


What's the reason for this?

2

There are 2 answers

2
VonC On

I just tested:

testing = !sh -c 'echo "$@"' {};

This does display all the parameters.

This is similar to "find: missing argument to -exec"

A -exec command must be terminated with a ; (so you usually need to type \; or ';' to avoid interpretation by the shell)

This would work too:

[alias]
    testing = "!f() { echo \"$@\"; }; f"
6
acanby On

If your sh is bash, then the Bash man page has some info:

-c string

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

Before you get a chance to access $@, Bash interprets the -c and will pass the subsequent arguments through as parameters to the sub shell. This means $0 will be the next value passed, which is 4 (essentially $@ and $0 are the same at this point because there is only one value).

If you run the sh with -v you will see slightly more about what is happening:

$ git testing 1 4
echo $@
4

So the echo $@ gets only 4 in its arguments. The -c will create a sub shell, and pass $@ though. Remember this contains only 4 now. This is where you are losing the 1.