如何在 bash 的别名中包含环境变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11172221/
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
How do I include an environment variable inside an alias for bash?
提问by Doboy
I am pretty new to bash, and I want to include an env for bash aliases.. I want to do something like the following
我对 bash 还很陌生,我想为 bash 别名包含一个 env .. 我想做如下事情
alias foo="bar $(baz)"
So that I could do something like the following
这样我就可以执行以下操作
> baz=40
> foo
and foo will expand to the command bar 40. Currently the above does not work because $(baz) is expanded while making the alias. Do I have to wrap this inside a function or something?
并且 foo 将扩展为 command bar 40。目前上述方法不起作用,因为 $(baz) 在创建别名时被扩展。我是否必须将其包装在函数或其他东西中?
回答by Kenneth Hoste
You need to use single quotes (') to prevent bash from expanding the variable when creating the alias:
您需要使用单引号 ( ') 来防止 bash 在创建别名时扩展变量:
$ alias foo='echo "$bar"'
$ bar="hello"
$ foo
hello
回答by ormaaj
Aliases don't have an "environment". An alias is simply a "dumb" text substitution. In the question, an environment variable isn't being used - only a shell variable. If you want to use the environment, use a function. In this case, there is no advantage to an alias over a function.
别名没有“环境”。别名只是一个“哑”文本替换。在这个问题中,没有使用环境变量 - 只有一个 shell 变量。如果要使用环境,请使用函数。在这种情况下,别名比函数没有优势。
$ alias foo='echo "$bar"'
$ bar=hi foo
This produces no output because the environment set for a simple command doesn't apply to expansions.
这不会产生任何输出,因为为简单命令设置的环境不适用于扩展。
$ alias foo=$'eval \'echo "$bar"\''
$ bar=hi foo
hi
If a function were used instead, there wouldn't be a problem.
如果改用一个函数,就不会有问题。
$ foo() { echo "$bar"; }
$ bar=hi foo
hi
When in doubt, always use a function.
如有疑问,请始终使用函数。
Edit
编辑
Technically, the above is bash-only. Doing this in a fully portable way is nearly impossible.
从技术上讲,上述内容仅适用于 bash。以完全可移植的方式执行此操作几乎是不可能的。
In dash, mksh, bash POSIX mode, and other POSIX shells you can do:
在 dash、mksh、bash POSIX 模式和其他 POSIX shell 中,您可以执行以下操作:
foo() { echo "$bar"; }
bar=hi command eval foo
However, this won't work in ksh93 or zsh. (I've already reported a bug for ksh93 but it may never be fixed.) In mksh and ksh93 you should instead define functions using the functionkeyword, but that isn't POSIX. I'm not aware of any solution that will work everywhere.
但是,这在 ksh93 或 zsh 中不起作用。(我已经报告了 ksh93 的一个错误,但它可能永远不会被修复。)在 mksh 和 ksh93 中,您应该改为使用function关键字定义函数,但这不是 POSIX。我不知道任何可以在任何地方使用的解决方案。
To make matters worse, extra exceptions are being added to POSIX 2008-TC1 so that the way environment assignments work will be even more complicated. I suggest not using them unless you really know what you're doing.
更糟糕的是,POSIX 2008-TC1 中添加了额外的例外,因此环境分配的工作方式将更加复杂。我建议不要使用它们,除非你真的知道你在做什么。

