for loop not working - syntax error at line 6: `end of file' unexpected

I have a file called test.dat which contains

a b

I have written a shell script called test.sh

for i in `cat test.dat`
do
echo $i
done

When i run this script using

sh test.sh

I get this message -

test.sh: syntax error at line 6: `end of file' unexpected

What is the problem.

Thanks,
Debojyoty

Your script works fine for me. Open the script in vi and enter the command :set list to see if you have any characters mucking up your script.

It also occurred to me that one of you back ticks could be a single quote as well, which would certainly cause your error.

for i in `cat test.dat' <=== single quote and not back tick
do
echo $i
done

$ sh test.sh
test.sh: syntax error at line 5: `end of file' unexpected
for i in `cat test.dat` <=== back tick
do
echo $i
done

$ sh test.sh
a
b

this is most recommended for reading a file using while loop.

while read line
do
echo $line
done<"test.dat"