user1519254
user1519254

Reputation: 1

Bash for loop error

I am trying out a simple bash script using for loop, and kept getting the following error:

'/test.sh: line 2: syntax error near unexpected token `do
'/test.sh: line 2: `do

The following is the code that is being used...

for animal in dog cat elephant
do
    echo "There are ${animal}s.... "
done

However, when I tried on other machines.. it is working no problem. Please help.

Upvotes: 0

Views: 371

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263207

Your test.sh script has Windows-style line endings. The shell sees each \r\n sequence as a \r character at the end of the line.

The shell is seeing do\r rather than do. Since \r sends the cursor to the beginning of the line, that's why you're seeing the quotation mark at the beginning of the line. Try

./test.sh 2>&1 | cat -A

to see what's actually in the error message.

Filter your test.sh script through something like dos2unix to correct the line endings. (Be sure to read the man page first; dos2unix, unlike most text filters, overwrites its input file.)

This is a common problem on Cygwin. Did you use a Windows editor to create the script?

Upvotes: 3

Related Questions