StevieD
StevieD

Reputation: 7433

Creating a git alias containing bash command substitution and an argument

Got this:

git diff $(git status -s | awk 'FNR == $LINE_NUM {print $2}')

...where line number is the file output by status.

Now I want to create an alias for this command in .gitconfig:

[alias]
diff-num = $WHAT_SHOULD_I_PUT_HERE?

I want this alias to run git's diff command based on the line number argument I'll type in on the command line. I'm new to bash and I'm not sure if I need a bash function to handle this or how to pass the argument into the substituted command.

Upvotes: 0

Views: 730

Answers (2)

StevieD
StevieD

Reputation: 7433

OK, got it worked out. Git alias looks like this:

diff-num = ! diff_num

Bash function is this:

diff_num () {
    line=${1:-1}
    git diff $(git status -s | awk 'FNR == '$line' {print $2}')
}

Function must be exported with the following bash command in your bash config file:

export -f diff_num

Upvotes: 1

jthill
jthill

Reputation: 60235

The usual form for this is to use the conventional ! shell escape, define an arbitrarily-named shell function and run that, git supplies it with your args. One of my goto's is lgdo,

git config alias.lgdo '!f() { git log --graph --decorate --oneline "${@---all}"; }; f'

also, I have gr and grl as git config --get-regexp {,--local} aliases:

[alias]
        grl = "!f() { git config --local --get-regexp \"${@-.}\"; }; f"
        gr = "!f() { git config --get-regexp \"${@-.}\"; }; f"

Upvotes: 3

Related Questions