简体   繁体   中英

What's wrong with my Git alias

I want an alias for git to delete a branch both from local and remote repositories. So, I've created one in my ~/.gitconfig :

[alias]
    erase = !"git push origin :$1 && git branch -D $1"

It works as expected, deletes branch from origin and local but in console I see extra line ( error: branch 'profile_endpoints' not found. ):

┌[madhead@MADHEAD-LAPTOP:/c/projects/b developing]
└─$ git erase profile_endpoints
To git@github.com:a/b.git
 - [deleted]         profile_endpoints
Deleted branch profile_endpoints (was abcdef0).
error: branch 'profile_endpoints' not found.

I'm using git version 1.8.0.msysgit.0 and git bash on Windows 7.

What am I missing?

The problem is that when you run a git alias, git tacks on the arguments at the end of the string. Try, eg:

[alias]
    showme = !echo git push origin :$1 && echo git branch -D $1

Then run:

$ git showme profile_endpoints
git push origin :profile_endpoints
git branch -D profile_endpoints profile_endpoints

There are various workarounds. One trivial one is to assume that this will be given one argument that will be appended, so:

[alias]
    showme = !echo git push origin :$1 && echo git branch -D

However, this version increases the danger of misuse:

$ git showme some oops thing
git push origin :some
git branch -D some oops thing

Another standard trick is to define a shell function so that all the tacked-on arguments are passed:

[alias]
    showme = !"f() { case $# in 1) echo ok, $1;; *) echo usage;; esac; }; f"

$ git showme some oops thing
usage
$ git showme one
ok, one

One that's a little bit iffier is to use a dummy "absorb extra arguments" command:

[alias]
    showme = !"echo first arg is $1 and others are ignored; :"

$ git showme one two three
first arg is one and others are ignored

My own personal rule is to switch to a "real" shell script as soon as the alias gets complicated. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM