1

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.

3
  • Just alias add, any additional parameters will be passed through. Commented May 5, 2016 at 15:32
  • @jonrsharpe Please mind those automatically added asterisks. Commented May 5, 2016 at 15:42
  • Oh I assumed they were to indicate that's the thing you wanted, not part of the branch name. Why do you want that? Commented May 5, 2016 at 15:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it, thank you. I found out that generated syntax is: a = !sh -c \"git add *$1*\". Please add it to your answer for future reference. Many people prefer to use .gitconfig file instead of adding config through console.
0

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

4 Comments

Please notice those asterisks that I want to add automatically. That's my entire point.
Can that be done in alias section? And without the loop?
mm I don't know, this is a different approach
It was a = !sh -c \"git add *$1*\" :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.