Robo Robok
Robo Robok

Reputation: 22815

How to make an alias for git add *name*?

I'm trying to create an alias for git add *name*, so I could use it like this:

git a foo

And it would call the following:

git add *foo*

How can I do it? I tried a = add *$1*, but it doesn't work.

Upvotes: 1

Views: 45

Answers (2)

Kevin M Granger
Kevin M Granger

Reputation: 2545

In order for shell variables ($1) to be evaluated in a git alias, it needs to be a shell git alias, instead of a built-in alias. These are aliases prefixed with a !.

git config alias.a '!sh -c "git add  *$1*"'

will do the trick. You could also directly add the line to your git config as follows:

[alias]
    a = !sh -c \"git add *$1*\"

However, if you want to support specifying multiple files, you'll need to make something more intricate, like a shell script:

#!/bin/bash
#file: $HOME/bin/git-a
newargs=()
for arg in "$@"; do
    newargs+=("*$arg*")
done
git add "${newargs[@]}"

Then make sure it's executable and in your $PATH. If it is, then git will find it and execute it when you type git a, without having to set up an alias.

Adding additional features, like passing through other flags to git add, is left as an exercise to you.

Upvotes: 3

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

Inside your home directory, look for a file called .gitconfig, and add the following:

[alias]:
    a = add

UPDATE:

create this file (gitadd.sh)

gitadd() {
    for ARG in "$@"
    do
        git add "./*$ARG*"
    done
}

usage:

  • add gitadd function to ~/.bash_aliases
  • reload it to take effect using source ~/.bashrc
  • use it like this: gitadd name

Upvotes: 0

Related Questions