我想在bash中创建一个别名,例如
git diff somefile
成为
git diff --color somefile
但我不想定义我自己的自定义别名,如
alias gitd = "git diff --color"
因为如果我习惯了这些自定义别名,那么我就无法在没有这些映射的机器上工作。
编辑:似乎bash不允许使用多字别名。除了创建别名之外,还有其他替代解决方案吗?
答案 0 :(得分:18)
要为命令创建更智能的别名,您必须编写一个包装函数,该函数与该命令具有相同的名称,并分析参数,转换它们,然后使用转换的参数调用实际命令。
例如,您的git
函数可以识别正在调用diff
,并在那里插入--color
参数。
代码:
# in your ~/.bash_profile
git()
{
if [ $# -gt 0 ] && [ "$1" == "diff" ] ; then
shift
command git diff --color "$@"
else
command git "$@"
fi
}
如果您想在diff
之前支持任何选项,并且仍然添加--color
,那么您必须使此解析变得更加智能。
答案 1 :(得分: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.
无需任何功能或别名。但函数包装器方法对于任何命令都是通用的;把那张卡贴在袖子上。
答案 2 :(得分:2)
Git有自己的方法来指定别名(http://git-scm.com/book/en/Git-Basics-Tips-and-Tricks#Git-Aliases)。例如:
git config --global alias.d 'diff --color'
然后您可以使用git d
。
答案 3 :(得分:1)
避免在bash中分配签名空白:
alias gitd="git diff --color"
答案 4 :(得分:1)
color.diff
配置选项设置为auto
。