.bashrc 中定义的别名在管道后不起作用

Ein*_*din 4 bash alias bashrc pipe

我遇到了以下问题。

我在.bashrc(和.bash_profile)中定义了一个别名:

alias echo2="echo"
Run Code Online (Sandbox Code Playgroud)

这很有效:

$ echo2 "test"
test
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试在重定向后使用它,则它不起作用:

ls | awk '{print "echo2 "$1}' | bash
bash: line 1: echo2: command not found
bash: line 2: echo2: command not found
...
Run Code Online (Sandbox Code Playgroud)

有人知道为什么吗?我怎样才能让它工作?

Dan*_*eck 6

您将其bash作为输入通过管道传输到新流程中。不过,该过程不会加载您的初始化脚本,因此没有定义别名。

检查部分INVOCATIONman bash:这取决于你所定义的别名文件,你需要做的bash过程中无论是登录shell( -l)或交互(-i)来加载该文件。

还有一个额外的限制:当 shell 不是交互式时,别名将被忽略。不过有一个解决方法:

   Aliases  are not expanded when the shell is not interactive, unless the
   expand_aliases shell option is set using shopt (see the description  of
   shopt under SHELL BUILTIN COMMANDS below).
Run Code Online (Sandbox Code Playgroud)

或者,您可以考虑使用 shell函数而不是别名。