leviathan898 leviathan898 - 5 months ago 19
Bash Question

BASH - Syntax error near unexpected token 'done'

I'm new to programming in bash and am trying to write a script. So far it's very rudimentary but I'm getting the above error with the

done
at the end.

for ((i = 1; i < 13; i++)) do
if [ "$i" -lt "4" ]; then
touch Block1/B8IT11"$i".txt
echo B8IT11"$i" created
else if [ "$i" -gt "3" -a "$i" -lt "7" ]; then
touch Block2/B8IT11"$i".txt
echo B8IT11"$i" created
else if [ "$i" -lt "6" -a "$i" -lt "10" ]; then
touch Block3/B8IT11"$i".txt
echo B8IT11"$i" created
else
touch Block4/B8IT11"$i".txt
echo B8IT11"$i" created
fi
done


To my eyes I can't see the issue, as the
if-else if-else
ends with
fi
and the
for
loop should terminate with the
done
.

I've done
cat -v
and even
dos2unix
it. Does anyone see something I'm missing?

Answer

There is no else if in bash. What you have is an else followed by a (nested) if construct. The outer else is unterminated (missing fi). Bash thinks you're still in an else block so it's not expecting done at this point:

for ((i = 1; i < 13; i++)) do
    if [ "$i" -lt "4" ]; then
        touch Block1/B8IT11"$i".txt
        echo B8IT11"$i" created
    else
        if [ "$i" -gt "3" -a  "$i" -lt "7" ]; then
            touch Block2/B8IT11"$i".txt
            echo B8IT11"$i" created
        else
            if [ "$i" -lt "6" -a  "$i" -lt "10" ]; then
                touch Block3/B8IT11"$i".txt
                echo B8IT11"$i" created
            else
                touch Block4/B8IT11"$i".txt
                echo B8IT11"$i" created
            fi
            done

Fix: Change all your else if to elif.