在bash中创建多字别名?

Sud*_*dar 12 git bash

我想在bash中创建一个别名,这样

git diff somefile
Run Code Online (Sandbox Code Playgroud)

git diff --color somefile
Run Code Online (Sandbox Code Playgroud)

但我不想定义自己的自定义别名

alias gitd = "git diff --color"
Run Code Online (Sandbox Code Playgroud)

因为如果我习惯了这些自定义别名,那么我就失去了在没有这些映射的机器上工作的能力.

编辑:似乎bash不允许多字别名.除了创建别名之外,还有其他替代解决方案吗?

Kaz*_*Kaz 19

要为命令创建更智能的别名,您必须编写一个与该命令同名的包装函数,该函数分析参数,转换它们,然后使用转换后的参数调用实际命令.

例如,您的git函数可以识别diff正在调用的函数,并在--color那里插入参数.

码:

# in your ~/.bash_profile

git()
{
  if [ $# -gt 0 ] && [ "$1" == "diff" ] ; then
     shift
     command git diff --color "$@"
  else
     command git "$@"
  fi
}
Run Code Online (Sandbox Code Playgroud)

如果你想在之前支持任何选项diff并且仍然需要添加--color,那么显然你必须使这种解析变得更加智能.

  • 您可能想使用“命令 git”而不是对路径进行硬编码。 (2认同)

Kaz*_*Kaz 7

更好的答案(针对这个特定情况).

git-config手册页:

   color.diff
       When set to always, always use colors in patch. When false (or
       never), never. When set to true or auto, use colors only when the
       output is to the terminal. Defaults to false.
Run Code Online (Sandbox Code Playgroud)

不需要任何功能或别名.但函数包装器方法对于任何命令都是通用的; 把那张卡贴在袖子上.


jca*_*llo 5

Git 有自己的方式来指定别名(http://git-scm.com/book/en/Git-Basics-Tips-and-Tricks#Git-Aliases)。例如:

git config --global alias.d 'diff --color'
Run Code Online (Sandbox Code Playgroud)

然后你可以使用git d.