bash: 无法在同一行中设置和使用别名

bash: unable to set and use alias in the same line

我希望第二行说 foo 而不是 command not found:

$ alias foo="echo bac" ; foo;
-bash: foo: command not found
$ foo
bac
$

为什么第二行不说foo?使用以下 shell 进行测试,行为相同:

Bash Reference Manual(强调我的)中描述了您所看到的行为:

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

想必其他 shell 也有这种行为。

要在bash的同一行中设置和使用alias,可以使用:

eval $'alias df5=df\ndf5 -h'

(学分:Hauke Laging's workaround + Kusalananda's workaround)。


命令解释:

  • 由于"an alias definition appearing on the same line as another command does not take effect until the next line of input is read"根据bash手册为Tom Fenech's ,我们使用eval并在alias定义和它的使用之间换行.
  • 来自Kusalananda's workaround

    "The $'...' is a "C string", and bash would expand the \n within it to a literal newline before passing it to eval.