在bash中没有正确调用函数

pro*_*eek 0 bash

我有这个bash代码,检查操作系统是Linux还是Mac,我使用函数isWhat从其他函数调用.

function isWhat 
{
  if [ `uname` == $1 ];
  then
    return 1
  else
    return 0  
  fi
}

function isLinux 
{
    return isWhat("Linux")
}

function isMac
{
    return isWhat("Darwin")
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了这些错误:

/functions.sh: line 13: syntax error near unexpected token `('
/functions.sh: line 13: `    return isWhat("Linux")'
runme.sh: line 7: isMac: command not found
Run Code Online (Sandbox Code Playgroud)

可能有什么问题?

Fat*_*ror 5

这不是你打电话给函数的方式bash.它们就像其他shell命令一样工作,即:

function isLinux 
{
    isWhat "Linux"
}
Run Code Online (Sandbox Code Playgroud)

此外,return冗余功能将返回上次命令运行的退出状态.如果你想要明确,你可以这样写:

function isLinux 
{
    isWhat "Linux"
    return $?
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我们指的是最佳实践,我倾向于建议符合POSIX的函数调用语法(`isLinux(){`没有`function`). (2认同)