Define git alias with the same name to shadow orig

2019-01-07 19:30发布

问题:

I'm trying to use to use the same name for an alias as the existing command, so that the alias shadows the original command (preventing me from deleting files off the working tree).

[alias]
   rm = rm --cached
   diff = diff --color

Unfortunatly this is not working. Does anyone know a workaround? Thanks.

Edit Setting color.diff = true gives colored output as default.

回答1:

For commands like rm --cached that don't have configurable options, your best bet is to just make an alias named differently. For example:

[alias]
        rmc = rm --cached

You may have already figured this out, but Git aliases cannot shadow existing Git commands. From the git-config man page:

To avoid confusion and troubles with script usage, aliases that hide existing git commands are ignored.



回答2:

As a workaround, you can define aliases in Bash to get the result you want. Here's something I just knocked up for a pet peeve of mine - that 'git add' is not verbose by default. (And there's no config setting for it).

Put this in your ~/.bash_profile or ~/.bash_rc

function do_git {
  cmd=$1
  shift
  extra=""
  if [ "$cmd" == "add" ]; then
    extra="-v"
  elif [ "$cmd" == "rm" ]; then
    extra="--cached"
  fi
  git="$(which git)"
  ex="$git $cmd $extra $@"
  ${ex}
}
alias  git='do_git'

Then just call it like normal:

$ git add .
add 'foo'


回答3:

This is the answer of Steve Bennett translated for oh-my-zsh

function do_git {
  cmd=$1
  shift
  extra=""
  if [ "$cmd" '==' "add" ]; then
    extra="-v"
  elif [ "$cmd" '==' "rm" ]; then
    extra="--cached"
  fi
  "`whence -p git`" "$cmd" "$extra" "$@"
}
alias  git='do_git'

The equals sign needs to be wrapped in quotes. And which doesn't work as it just return that 'git' is an alias.



标签: git alias