Tip: Bash scripting in Cygwin without \r syntax errors

Archive for June, 2007

Tip: Bash scripting in Cygwin without \r syntax errors

Posted by

The standard conventions when Bash scripting apply in the Windows Cygwin environment. If you are like me, you will find it much easier to edit your .sh scripts in Notepad orĀ Notepad++ rather than vi or nano. However, you will likely run into the following problem:

./script.sh: line 1: syntax error near unexpected token ‘$’do\r”

Or …

./script.sh: line 1: $’\r’: command not found

The cause is easy to see. The script is choking on \r, which is the carriage return character (0x0D or 13). Windows and Windows editors rely upon the double return of the linefeed (\n or 0x0A or 10) plus the carriage return. Macs only use the carriage return (\r). Unix? It only uses the linefeed (\n).

The resolution is to strip out the extra carriage return at the end of every script line. Cygwin provides an easy tool to accomplish this. The dos2unix.exe command will set all linefeeds to the single (\n) character.

$ dos2unix.exe script.sh
dos2unix: converting file script.sh to Unix format …