防止 bash 别名在 shell 启动时评估语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13260969/
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
Prevent bash alias from evaluating statement at shell start
提问by Martin Konecny
Say I have the following alias.
假设我有以下别名。
alias pwd_alias='echo `pwd`'
This alias is not "dynamic". It evaluates pwdas soon as the shell starts. Is there anyway to delay the evaluation of the expression in the ticks until the alias's runtime?
这个别名不是“动态的”。它pwd在 shell 启动后立即进行评估。无论如何,是否可以将刻度中的表达式的计算延迟到别名的运行时?
回答by jordanm
What you really want is a function, instead of an alias.
您真正想要的是一个函数,而不是别名。
pwd_alias() {
   echo "$PWD"
}
Aliases do nothing more than replace text. Anything with complexity calls for a function.
别名无非是替换文本。任何具有复杂性的事物都需要一个函数。
回答by Raphael Payen
As jordanm said, aliases do nothing more than replace text.
If you want the argument of echo to be the output of pwd expanded by bash, then I don't understand your question.
If you want the argument of echo to be `pwd` with the backquotes kept, it's indeed possible, for example:
正如 jordanm 所说,别名无非是替换文本。
如果您希望 echo 的参数是 bash 扩展的 pwd 的输出,那么我不明白您的问题。
如果您希望 echo 的参数为 `pwd` 并保留反引号,则确实可以,例如:
alias a="echo '\`pwd\`'"
So, if instead of echo you have something which does backquote expansion in its own runtime, maybe that's what you want.
所以,如果不是 echo 你有一些东西在它自己的运行时进行反引号扩展,也许这就是你想要的。
回答by Lipongo
I do not believe you can change the evaluation from occurring at shell start.  Since the processes of creating the alias is run at shell start the pwdis evaluated then.  You could simple change the alias to just run pwdwithout the back ticks as pwdoutputs without the need to echo.  A simple way to resolve this is to change from using an alias to a shell script in your path if you do not wish to change from using an alias.
我不相信您可以更改在 shell 启动时发生的评估。由于创建别名的过程是在 shell 启动时运行的,因此pwd会进行评估。您可以简单地将别名更改为只运行pwd而无需回显作为pwd输出。解决此问题的一个简单方法是,如果您不想更改为使用别名,则在您的路径中从使用别名更改为 shell 脚本。
#!/bin/bash
pwd

