在 bash 中创建多词别名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10169582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create multi-word alias in bash?
提问by Sudar
I want to create an alias in bash, such that
我想在 bash 中创建一个别名,这样
git diff somefile
becomes
变成
git diff --color somefile
But I don't want to define my own custom alias like
但我不想定义我自己的自定义别名
alias gitd = "git diff --color"
because if I get used to these custom alias, then I loose the ability to work on machines which don't have these mappings.
因为如果我习惯了这些自定义别名,那么我就无法在没有这些映射的机器上工作。
Edit: It seems bash doesn't allow multi-word alias. Is there any other alternative solution to this apart from creating the alias?
编辑:似乎 bash 不允许多字别名。除了创建别名之外,还有其他替代解决方案吗?
采纳答案by Kaz
Better answer (for this specific case).
更好的答案(对于这种特定情况)。
From git-configman page:
从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.
No function or alias needed. But the function wrapper approach is general for any command; stick that card up your sleeve.
不需要函数或别名。但是函数包装器方法对于任何命令都是通用的;把那张卡片贴在袖子上。
回答by Kaz
To create a smarter alias for a command, you have to write a wrapper function which has the same name as that command, and which analyzes the arguments, transforms them, and then calls the real command with the transformed arguments.
要为命令创建更智能的别名,您必须编写一个与该命令同名的包装函数,该函数分析参数、转换它们,然后使用转换后的参数调用实际命令。
For instance your gitfunction can recognize that diffis being invoked, and insert the --colorargument there.
例如,您的git函数可以识别diff正在调用的函数,并在--color那里插入参数。
Code:
代码:
# in your ~/.bash_profile
git()
{
if [ $# -gt 0 ] && [ "" == "diff" ] ; then
shift
command git diff --color "$@"
else
command git "$@"
fi
}
If you want to support any options before diffand still have it add --color, you have to make this parsing smarter, obviously.
如果您想之前支持任何选项diff并且仍然让它 add --color,那么显然您必须使这个解析更智能。
回答by jcarballo
Git has its own way to specify aliases (http://git-scm.com/book/en/Git-Basics-Tips-and-Tricks#Git-Aliases). For example:
Git 有自己的方式来指定别名(http://git-scm.com/book/en/Git-Basics-Tips-and-Tricks#Git-Aliases)。例如:
git config --global alias.d 'diff --color'
Then you can use git d.
然后你可以使用git d.
回答by user unknown
Avoid blanks around assignment sign in bash:
避免在 bash 中的赋值符号周围出现空格:
alias gitd="git diff --color"
回答by Ignacio Vazquez-Abrams
You're barking up the wrong tree. Set the color.diffconfig option to auto.
你叫错了树。将color.diff配置选项设置为auto.

