【问题标题】:Bash syntax error near unexpected token `else'意外标记“else”附近的 Bash 语法错误
【发布时间】:2016-07-27 11:57:50
【问题描述】:

我用 bash 编写了一个简单的脚本。但是当我运行它时,它会在标题中给出错误。

#!/bin/bash

unix_OS=`uname`

function_aix()
 {

   echo "This is AIX os"

  }


function_other()

 {

   echo " This could either be Linux/Solaris/Hp-UX"

  }

if [ $unix_OS == AIX ]
then

 echo "executing aix function"
  function_aix()

else

 echo "other function"
  function_other()


fi

任何建议都会有所帮助!

【问题讨论】:

  • 使用函数时,不能/不能使用()s。只需传递所需的任何参数,即myFn arg1 "arg 2" arg3。祝你好运。
  • 删除括号后,它工作正常。非常感谢:)

标签: shell


【解决方案1】:

当你想在 bash 中调用一个函数时,你不应该把()
如果你的函数有参数,你可以把它们放在函数调用旁边:my_function "first" "second"

#!/bin/bash

unix_OS=`uname`

function_aix()
{
   echo "This is AIX os"
}

function_other()
{
   echo " This could either be Linux/Solaris/Hp-UX"
}

if [ $unix_OS == "AIX" ]
then
  echo "executing aix function"
  function_aix
else
  echo "other function"
  function_other
fi

【讨论】:

  • 我用 nawk 编写了一个运行正常的脚本。但是,我收到一个建议,即大多数服务器中都没有安装“nawk”。请更新它以使用 awk。当我在 solaris 中使用 awk 时,出现以下错误。 awk:第 1 行附近的语法错误 awk:在第 1 行附近退出
【解决方案2】:

调用函数时,函数名不需要带括号()。 替换行如下:

.... 
if [ $unix_OS == "AIX" ]
 then
    echo "executing aix function"
    function_aix
else
    echo "other function"
    function_other
....

【讨论】:

  • 删除括号后,它工作正常。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2014-08-30
  • 2014-02-26
  • 2018-12-18
  • 2014-01-20
  • 2015-12-11
  • 2021-07-29
  • 2014-06-04
  • 1970-01-01
相关资源
最近更新 更多