Sep 14

先看这个脚本:

#!/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: , , ,