bash_profile 中的别名自行执行

Alias in bash_profile executes by itself

我在~/.bash_profile中设置了一个别名如下:

alias lcmt="git show $(git log --oneline | awk '{print ;}' | head -n 1)"

但是,每当我打开终端 window,我都会看到:

fatal: Not a git repository (or any of the parent directories): .git

我已经能够将它缩小到那个特定的别名,因为当我注释掉它时,没有错误消息。为什么它在 OS X 上自行求值?我可以阻止它这样做吗?

双引号表达式中的 $(...) 在赋值时执行,创建别名。您可以通过转义 $(...)$ 来避免这种情况。你想对 awk 命令中的 </code> 做同样的事情:</p> <pre><code>alias lcmt="git show $(git log --oneline | awk '{print $1}' | head -n 1)"

Shell 函数在很多方面都比别名好,包括没有像别名那样奇怪的引用。定义一个 shell 函数来做到这一点很容易:

lcmd() { git show $(git log --oneline | awk '{print ;}' | head -n 1); }

我还有另外两个建议:在 $( ) 表达式周围加上双引号,并让 awk 在第一行之后停止:

lcmd() { git show "$(git log --oneline | awk '{print ; exit}')"; }