Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing syntax error near unexpected token 'done'

I am trying to learn shell scripting, so I created a simple script with a loop that does nothing:

#!/bin/bash
names=(test test2 test3 test4)
for name in ${names[@]}
do
        #do something
done

however, when I run this script I get the following errors:

./test.sh: line 6: syntax error near unexpected token done'
./test.sh: line 6: done'

What have I missed here? are shell scripts 'tab sensitive'?

like image 455
fenerlitk Avatar asked May 10 '12 12:05

fenerlitk


2 Answers

No, shell scripts are not tab sensitive (unless you do something really crazy, which you are not doing in this example).

You can't have an empty while do done block, (comments don't count) Try substituting echo $name instead

#!/bin/bash
names=(test test2 test3 test4)
for name in ${names[@]}
do
       printf "%s " $name
done
printf "\n"

output

test test2 test3 test4
like image 120
shellter Avatar answered Sep 19 '22 13:09

shellter


dash and bash are a bit brain-dead in this case, they do not allow an empty loop so you need to add a no op command to make this run, e.g. true or :. My tests suggest the : is a bit faster, although they should be the same, not sure why:

time (i=100000; while ((i--)); do :; done)

n average takes 0.262 seconds, while:

time (i=100000; while ((i--)); do true; done)

takes 0.293 seconds. Interestingly:

time (i=100000; while ((i--)); do builtin true; done)

takes 0.356 seconds.

All measurements are an average of 30 runs.

like image 20
Thor Avatar answered Sep 18 '22 13:09

Thor