【问题标题】:BASH - While loop errorBASH - While 循环错误
【发布时间】:2015-12-06 18:07:34
【问题描述】:

使用此代码我收到此错误,并且我的功能不可用:

Erreur de syntaxe près du symbole inattendu «

   function my_func{ 
    while read Port
    do
            CHECK_HG=`raidcom get host_grp -port $Port -IH${CCI_INST} |grep -iw ${HOST}`
            if [ ! -z "$CHECK_HG" ]; then
                    export HMO=`raidcom get host_grp -port $Port -IH${CCI_INST} | grep -i ${HOST} | awk -F " " '{print \$5}'`
                    if [ $HMO == "LINUX/IRIX" ]; then
                            HMO=`echo $HMO | awk -F "/" '{print \$1}'`
                    fi
                    #comment
                    NBPort=`expr $NBPort + 1`
                    #comment
                    PORT_HG=$PORT_HG"$Port;\n"
                    fi
    done < <(echo -e "$TARGET_PORTS")
}

因此,当我更改循环时,我没有收到任何错误,但我会丢失变量中的所有数据以在主脚本中恢复。

function my_func{
    echo -e "$TARGET_PORTS" | while read Port
    do
            CHECK_HG=`raidcom get host_grp -port $Port -IH${CCI_INST} |grep -iw ${HOST}`
            if [ ! -z "$CHECK_HG" ]; then
                    export HMO=`raidcom get host_grp -port $Port -IH${CCI_INST} | grep -i ${HOST} | awk -F " " '{print \$5}'`
                    if [ $HMO == "LINUX/IRIX" ]; then
                            HMO=`echo $HMO | awk -F "/" '{print \$1}'`
                    fi
                    #comment
                    NBPort=`expr $NBPort + 1`
                    #Comment
                    PORT_HG=$PORT_HG"$Port;\n"
                    fi
    done
}

有什么想法吗? 非常感谢。

【问题讨论】:

  • 也许尝试在 while 循环结束时删除一个 '
  • 不...同样的错误:完成
  • 您正在使用 bash 以外的 shell 执行脚本,并且该 shell 不理解进程替换。
  • 更简单:for Port in $TARGET_PORTS;

标签: bash loops while-loop


【解决方案1】:

您的重定向看起来适合 bash 脚本,其格式如 https://stackoverflow.com/a/28927847/3220113 中所述。
你能添加一个shebang(脚本第一行的#!/bin/bash),试图强制它进入bash吗?

另一个解决方案(当您需要在 AIX/Solaris 上的 ksh 和 bash 中运行相同的脚本时很好)是将 while 更改为 for 循环:

for Port in $(echo -e "$TARGET_PORTS") do
   ...
done

【讨论】:

  • 谢谢你,脚本是用 sh "Path/script...." 启动的。使用 bash "Path/script...." 它的工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2013-06-13
相关资源
最近更新 更多