函数内部别名

Alias inside function

bash -c 'shopt -s expand_aliases

a() {
    alias myfunc="echo myfunc"
}

main() {
    a
    myfunc
}

main'

a函数用于给一些命令起别名,这些命令在main函数中使用。

输出:

environment: line 8: myfunc: command not found

这是预期的行为,在 the manual 中解释如下:

Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command.

在这种情况下,这意味着 main 中的 myfunc 不会扩展为 echo myfunc,除非您的脚本 调用 amain.

的定义之上定义它

我相信大家都很清楚 shell 在调用该函数之前不会在函数定义内执行命令。因此,在 main 之上定义 a 没有任何区别; myfunc 直到调用 a 才被定义。

比较这两个:

$ bash -O expand_aliases -c '
foo() { bar; }
alias bar=uname
foo'
environment: line 1: bar: command not found
$ bash -O expand_aliases -c '
alias bar=uname
foo() { bar; }
foo'
Linux

解决方法是避免在 shell 脚本中使用别名。功能更好。