How to embed bash script directly inside a git alias


Question

Can I embed the following bash shell code:

for name in $(git diff --name-only $1); do git difftool $1 $name & done

directly into the creation of a git alias:

git config --global alias.diffall ***my-bash-code-here***

This leads on from my previous question/answer on SO, where I put the code into a .sh file and then aliased to the file:

git config --global alias.diffall '!sh diffall.sh'

But in the never-ending quest for simplicity, there's gotta be a way to skip the file and insert code directly into the alias? I can't figure out the format...

1
77
5/23/2017 11:47:22 AM

Accepted Answer

git config --global alias.diffall '!sh diffall.sh'

This is redundant in one way. If you are going to add 'diffall.sh' into your $PATH anyway, why not save it as 'git-diffall', and save yourself from declaring an alias. Yes, "git diffall" will run it.

90
8/21/2009 1:29:58 AM

To run commands inside of a git alias, and in particular to pass arguments to those commands, you will likely have to create a temporary function which you then immediately invoke:

$ vim ~/.gitconfig
...
[alias]
    # compare:
    foo = "! echo begin arg=$1/$2/end"
    foo2 = "!f() { echo "begin arg=$1/$2/end"; }; f"

In this example, the function is probably what you need (and is also more flexible as to what you can do in a single "statement"); and you can probably tell that for both options, the remaining args to the git command are simply passed as args to the alias, regardless if it's "echo" or "f"; invoking the function simply consumes the args, ignoring what's not explicitly used:

$ git foo a b c
begin arg=a/b/end a b c

$ git foo2 a b c
begin arg=a/b/end

Another example (lists all aliases, based on matching pattern) (note: you can keep reusing the same function name "f()" throughout the .gitconfig):

[alias]
    alias = "!f() { git config --get-regexp "^alias.${1}$" ; }; f"

The first returns the alias for just "foo$", the second for "foo.*":

$ git alias foo
alias.foo ! echo begin arg=$1/$2/end

$ git alias 'foo.*'
alias.foo ! echo begin arg=$1/$2/end
alias.foo2 !f() { echo begin arg=$1/$2/end; }; f

(nb: actual results may vary based on shell; I'm using this with bash on Linux, Unix & Cygwin (Windows).)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon