arekolek arekolek - 5 months ago 11
Bash Question

Abbreviate commonly used option to multiple git commands

I sometimes use

git diff
with a
option to get the changes displayed inline and for whole words only.

Since I noticed that I'm using it a bit, I've made a git alias for
diff --color-words='\w+|.'

But now I notice, there are many other places where I'd like to use the same option, like
git show
git stash show -p
git log -p
and more probably. So it's impossible to predict where I might need that option in the future.

I've tried this:

$ git config --global alias.words "--color-words='\w+|.'"
$ git diff words
fatal: ambiguous argument 'words': unknown revision or path not in the working tree
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

And this:

$ git config --global alias.--words "--color-words='\w+|.'"
error: invalid key: alias.--words

Is there any way to create an alias to an arduous option, so I can use it with various commands and save on typing and thinking?


Could use a function:

git() {
    # "${@}" is an array of the parameters sent to the method
    for i in "${@}"; do
       # If the parameter equals "words"
       if [[ "$i" = "words" ]]; then

    # If "words" was a parameter (see above)
    if [[ "$ISWORDS" ]]; then
        # "${@}" is an array of the parameters sent to the method
        for i in "${@}"; do
            declare -a OTHERPARAMS=()

            # Add every parameter to OTHERPARAMS, apart from "words"
            if [[ ! "$i" = "words" ]]; then

         # Call /usr/bin/git with every parameter except "words", and 
         # add the extra parameter --color-words too 
         /usr/bin/git "${OTHERPARAMS[@]}" --color-words='\w+|.'
         # Else, just call /usr/bin/git with all parameters normally
         /usr/bin/git "${@}"

That overrides the git command, calling it regularly with a function from the path if the parameter "words" isn't found. If it is, it removes that from the parameters, calls the command with the other parameters and an extra parameter for the --colour-words, in place of "words"