/bin/sh 与 /bin/bash 中的 alias

2019-09-14 – 12:10 下午 --- 31 次阅读

先看这个脚本:

#!/bin/bash
alias elog="logger -t $0 -s"
elog() {
    logger -t $0 -s "$@"
}
elog "hahahaha"
test123(){
    elog "i am in function!"
}
test123

运行后提示:

elog: command not found

如果换成 #!/bin/sh 则无问题:

#!/bin/sh
alias elog="logger -t $0 -s"
elog() {
    logger -t $0 -s "$@"
}
elog "hahahaha"
test123(){
    elog "i am in function!"
}
test123

执行后:

<13>Sep 14 11:59:48 /root/init.d/testme: hahahaha
<13>Sep 14 11:59:48 /root/init.d/testme: i am in function!

参考:Execute a passed alias inside a function?

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. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

修改为:(函数形式)

#!/bin/bash
elog() {
    logger -t $0 -s "$@"
}
elog "hahahaha"
test123(){
    elog "i am in function!"
}
test123

可行。 :roll: :roll: :roll:

再参考:Linux 环境中 alias 不生效问题

Tags: , , ,
点击显示引用框
引用本文,复制粘贴...

点击可把本文加入多个网络分享站点

您还可以参考以下文章:


标签相关

您必须 登录 才能发表评论.