为什么非交互式 Bash shell 中的别名不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1615877/
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
Why aliases in a non-interactive Bash shell do not work
提问by nisah
I am trying to use aliases in a non-interactive bash shell. I have defined my aliases in ~/.bashrcand I have set the variable BASH_ENV=~/startUpFile. The contents of the startUpFile are source ~/.bashrc.
我正在尝试在非交互式 bash shell 中使用别名。我已经定义了我的别名~/.bashrc并且我已经设置了变量BASH_ENV=~/startUpFile. startUpFile 的内容是source ~/.bashrc.
I can see that my aliases are recognized, when I execute the aliascommand. However, if I try to use an alias defined in ~/.bashrc, Bash can't recognized it. It gives me the unknown command error.
当我执行alias命令时,我可以看到我的别名被识别。但是,如果我尝试使用 中定义的别名~/.bashrc,Bash 将无法识别它。它给了我未知的命令错误。
With the TCSH shell it is pretty easy to do this because the ~/.cshrcfile is always read.
使用 TCSH shell 很容易做到这一点,因为~/.cshrc文件总是被读取。
Any ideas how I can do this with a Bash shell?
我有什么想法可以用 Bash shell 做到这一点吗?
采纳答案by Jim Lewis
The command shopt -s expand_aliaseswill allow alias expansion in non-interactive shells.
该命令shopt -s expand_aliases将允许在非交互式 shell 中扩展别名。
回答by Michael Dillon
.bashrcis only processed by interactive shells.
.bashrc仅由交互式 shell 处理。
In addition, aliases are not expanded when the shell is not interactive, unless the expand_aliasesshell option is set using shopt. Unless, of course, POSIX mode is invoked by calling the shell with the name shinstead of bash.
此外,当 shell 不是交互式时,别名不会被扩展,除非expand_aliasesshell 选项是使用shopt. 当然,除非通过使用名称sh而不是bash.
People who use aliases a lot often source their .bashrcat the end of their profile so that the aliases are there even for non-interactive shells. This might not be the best way, but it is pretty common.
经常使用别名的人通常.bashrc在其个人资料的末尾获取别名,这样即使对于非交互式 shell,别名也存在。这可能不是最好的方法,但它很常见。
It's things like this that lead me to believe that in the 21st century we should abandon shell scripts in favor of a full-blown language like Python. It's a lot more predictable.
正是这样的事情让我相信,在 21 世纪我们应该放弃 shell 脚本,转而支持像 Python 这样的成熟语言。它的可预测性要强得多。
回答by Vinko Vrsalovic
You have to
你必须
shopt -s expand_aliases
in the file pointed to in your BASH_ENV
在您指向的文件中 BASH_ENV
回答by tomaszbak
I had similar issue, in the end, I found out that ~/.bashrc was all I needed.
我有类似的问题,最后,我发现 ~/.bashrc 是我所需要的。
However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :
但是,在 Ubuntu 中,我不得不注释停止处理 ~/.bashrc 的行:
If not running interactively, don't do anything
[ -z "$PS1" ] && return

