非交互式别名 bash

Aliases in non-interactive bash

我想让别名在非交互式环境中工作 bash。我运行以下命令:

bash -c "alias toto=ls; shopt -s expand_aliases; alias toto=ls; toto"

我得到以下信息:

bash: toto : commande not found

我做错了什么?

来自man bash

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.

这意味着,即使在交互式 shell、

alias toto=ls; toto

不行。别名定义和调用之间必须有一个换行符。所以,

bash -c 'shopt -s expand_aliases; alias toto=ls
toto'

应该可以。