1

I am trying to lean Bash scripting from cygwin. When i manually type the following lines in command prompt, everything works and I see that the number from 1 to 10 are printed on the screen.

for i in {1..10}; do
    echo $i;
done

However, if I save the script into a file (test.sh) and run "./test.sh", I was shown the following errors

./test.sh: line 1: syntax error near unexpected token `$'do\r''
'/test.sh: line 1: `for i in {1..10}; do

This seems very strange to me. i am wondering how come the same script runs fine in command line but not from a file.

Thanks, Derek

defoo
  • 5,159
  • 11
  • 34
  • 39
  • works fine for me (both cmd-line and in script-file) in bash on ubuntu. – aioobe Nov 03 '10 at 21:26
  • What text editor are you using to edit the file? It seems possible that your script might be in RTF or other non-plain-text format. – Greg Hewgill Nov 03 '10 at 21:44
  • i was using GVIM in windows. I will try to use :set fileformat=unix to force to save file with unix encoding. Will report back tmr. – defoo Nov 05 '10 at 04:27
  • yep, changing the text file to unix encoding works! – defoo Nov 05 '10 at 13:35

3 Answers3

9

The \r is a hint. Your file probably has CRLF (\r\n) line endings, which the bash interpreter does not handle gracefully. Change your editor settings to use Unix-style (\n) line endings, or run /usr/bin/dos2unix <file> on your file to reset the line endings.

mob
  • 117,087
  • 18
  • 149
  • 283
0

Another possible solution using unix text editor vi:

open file in vi edit with vi filename.sh command;

type in vi :set ff=unix command;

save file with :wq

It will save the file with unix line endings.

Bfcm
  • 2,686
  • 2
  • 27
  • 34
0

I am getting the same error in Notepad++. From this post, I changed Edit --> EOF Convertion, selected Unix/OSX Format, fixed this issue.

Jirong Hu
  • 2,315
  • 8
  • 40
  • 63