0

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.

2
  • does the file start with #!/bin/sh ? I suspect its an inconsistancy between the shells that its running in. You know what they say... it's easier to port a shell than a shell script Commented Jul 11, 2012 at 22:44
  • Check to see if there are Windows-style line endings: stackoverflow.com/questions/4841235/… Commented Jul 11, 2012 at 22:46

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Also you can detect the offending chars using cat -v test.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.