简体   繁体   中英

How to fix “syntax error near unexpected token `done' ” in a nested loop in bash?

I am writing a script that will loop through columns to find an instance of a word.

I decided I do it through nested loops and after executing my code, I get this error:

./gallupscript.sh: line 115: syntax error near unexpected token done' ./gallupscript.sh: line 115: done'

Here is the area where my code fails:

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

This code is expected to output the names (in first columns) where the word is matched with the one I am searching for.

You are not closing your if statement, it doesn't have to do with for .

Use the following code instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM