Search code examples
bashcygwin

the same bash script in command line doesn't work when run from a file


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


Solution

  • 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.