0

I'm on windows 7 using Cygwin.

My script and text file are located in the same directory.

#!/bin/bash
while read name; do
echo "Name read from file - $name"
done < /home/Matt/servers.txt

I get this error and I don't know why because this is correct while loop syntax..?

u0146121@U0146121-TPD-A ~/Matt
$ ./script.sh
./script.sh: line 4: syntax error near unexpected token `done'
./script.sh: line 4: `done < /home/Matt/servers.txt'

Can anybody tell me what I'm doing wrong? I think it's because I'm on windows and using Cygwin.

  • Do you mean it worked on Unix? – golimar Jul 1 '13 at 15:35
  • @golimar no never tested it – mkrouse Jul 1 '13 at 15:42
  • why don't you do a for loop? IMHO it would be much more readable (sorry it does not answer the question) – pataluc Jul 1 '13 at 16:03
  • @pataluc: Because while read... is often the recommended method. – grawity Jul 1 '13 at 16:10
  • 1
    Check the script for DOS-style line endings by printing it with cat -v /path/to/script and looking for "^M" at the end of lines." This doesn't really look like the errors I'd expect from this, but with Cygwin it's best to check. – Gordon Davisson Jul 2 '13 at 7:28
0

The previous answer is correct in that Windows will place \r\n but *nix systems will only accept \n. However there is an extremely easy way to solve this on a Windows machine.

In a text editor such as Textpad, choose "Save As", and under the filename you can choose "Line Ending". Here, save it as "UNIX", and the file will be properly encoded with \r and your scrips will work just fine.

0

This script has CR LF line endings. This is more visible with od.

$ od -c script
0000000   #   !   /   b   i   n   /   b   a   s   h  \r  \n   w   h   i
0000020   l   e       r   e   a   d       n   a   m   e   ;       d   o
0000040  \r  \n   e   c   h   o       "   N   a   m   e       r   e   a
0000060   d       f   r   o   m       f   i   l   e       -       $   n
0000100   a   m   e   "  \r  \n   d   o   n   e       <       /   h   o
0000120   m   e   /   M   a   t   t   /   s   e   r   v   e   r   s   .
0000140   t   x   t  \r  \n
0000145

As you can see, I have \r (carriage return) and \n (line feed) characters at the end of each line where you should only have \n characters. This is a result of a compatibility issue between Windows and *nix systems. Bash has difficulty dealing with the \r characters.

You can fix your script by using a utility like dos2unix or by running the following sed command:

sed -i 's/\r$//' script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.