函数不适用于 sh(但适用于 bash)

function doesn't work with sh (but works for bash)

当我写一个定义了函数的shell脚本时,我发现使用sh执行时出错,使用bash得到正确答案。这是一个演示:

test.sh

的内容
#!/bin/sh 
function hello {
   echo "hello "
}
hello world

"bash test.sh"的输出是:hello world

"sh test.sh" 的输出会给我错误。

为什么在脚本中包含定义的函数时sh无法得到正确的答案?我没有在网上找到答案。谢谢!


更新: 删除 "function" 关键字后,我发现了另一个问题。原来,在 Ubuntu 中,sh 被 link 编辑为 dash。 dash 的语法与 bash 略有不同。

  1. 定义函数时,避免使用关键字"function",这种格式是ksh引入的。

  2. 比较两个字符串时,避免使用“==”。只需使用“=”来比较两个字符串。

  3. 还有更多变化。请参考以下link:

    https://wiki.ubuntu.com/DashAsBinSh

Bash 和 sh 不共享完全相同的语言。

#!/bin/sh
hello() {
 echo "hello "
}

hello "world"

注意函数定义中缺少 function 关键字和 ()

关于 function 关键字:POSIX specifies that a function definition has this form:

fname() compound-command[io-redirect ...]

(注意没有 function 关键字)。此外,在 Reserved Words section 你会发现:

The following words may be recognized as reserved words on some implementations (when none of the characters are quoted), causing unspecified results:

[[ ]] function select

所以如果你想要一个可移植的函数定义,不要使用function关键字。

使用 Internet 了解更多信息,但要注意差异以了解如何为 sh 编写工作脚本。