【问题标题】:How to fix "syntax error near unexpected token `done' " in a nested loop in bash?如何在bash的嵌套循环中修复“意外标记‘完成’附近的语法错误”?
【发布时间】:2019-01-30 00:54:13
【问题描述】:

我正在编写一个脚本,它将遍历列以查找单词的实例。

我决定通过嵌套循环执行此操作,但在执行我的代码后,我收到此错误:

./gallupscript.sh:第 115 行:意外标记附近的语法错误 done' ./gallupscript.sh: line 115:done'

这是我的代码失败的区域:

token=2 #token is the column number
starter=0
s1="First" ; s2="Second" ; s3="Third" ; s4="Fourth" ; s5="Fifth"
s=s ; a=1
while [ $token -le 6 ]
do
    cat gallup.csv | cut -d',' -f"$token" | grep -n $strength1 | cut -d':' -f1 > str1
    if [ -s str1 ]
    then
        for i in $(cat str1)
        do
            if [[ $i -ne $number && $starter -eq 0 ]]
            then
                save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
                s=s ; s+=$a ; starter=1
                printf "-- $strength1 --"
                printf "${!s} Strength: $save"
            elif [[ $i -ne $number && $starter -ne 0 ]]
            then
                save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
                printf ", $save"
            fi
        done
    starter=0
    a=$((a+1))
    token=$((token+1))
    echo #new line
done

此代码应输出与我正在搜索的单词匹配的名称(在第一列中)。

【问题讨论】:

  • shellcheck.net 会告诉你错误的确切位置:你的if [ -s str1 ] 没有fi
  • 顺便说一句,见DontReadLinesWithFor;使用printf 时,为变量使用带占位符的格式字符串(printf '-- %s --' "$strength1"printf ', %s' "$save"),以防止这些变量的内容被格式说明符误解;并修复 shellcheck.net 识别的各种其他引用问题。
  • 哇,非常感谢!我不敢相信我错过了哈哈
  • ...根本不知道为什么要使用 str1 文件,而不仅仅是将管道捕获到变量中。甚至可以直接将其捕获到数组中:readarray -t items < <(cut -d',' -f"$token" <gallup.csv | grep -n "$strength1" | cut -d':' -f1); for item in "${items[@]}"; do ...
  • 感谢您的提示,我一定会使用它。

标签: bash


【解决方案1】:

您没有关闭您的if 语句,它与for 无关。

请改用以下代码:

token=2 #token is the column number
starter=0
s1="First" ; s2="Second" ; s3="Third" ; s4="Fourth" ; s5="Fifth"
s=s ; a=1
while [ $token -le 6 ]
do
    cat gallup.csv | cut -d',' -f"$token" | grep -n $strength1 | cut -d':' -f1 > str1
    if [ -s str1 ]
    then
        for i in $(cat str1)
        do
            if [[ $i -ne $number && $starter -eq 0 ]]
            then
                save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
                s=s ; s+=$a ; starter=1
                printf "-- $strength1 --"
                printf "${!s} Strength: $save"
            elif [[ $i -ne $number && $starter -ne 0 ]]
            then
                save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
                printf ", $save"
            fi
        done
    fi   #    <------------ add this line
    starter=0
    a=$((a+1))
    token=$((token+1))
    echo #new line
done

【讨论】:

  • How to Answer,“回答好问题”部分,注意“在帮助中心定义”链接,以及后面的“一些问题仍然离题”列表中的#2关联。由拼写错误引起的问题应该关闭,而不是回答 - 通过添加答案,您参与阻止 OP 自己删除问题(其他参与者是任何支持者)。
猜你喜欢
  • 2015-05-10
  • 2015-01-01
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2014-02-26
  • 2018-12-18
相关资源
最近更新 更多