Thursday, 2 October 2014

Windows New Lines Cause \r Scripting Errors

Using notepad++ to write Linux or Unix shellscripts creates scripts where each line ends in Windows format <line feed><carriage return> rather than Unix format <carriage return> new lines.

This will typically throw up an error when trying to run a script, for example:

$ ./ -s UC1 -rUC2 user1 user2 user3
./ line 33: $'\r': command not found
./ line 36: syntax error near unexpected token `$'in\r''
'/ line 36: `   case $value in

This can be fixed in notepad++ in the Settings menu:

Settings / Preferences / New Document and change the Format (Line ending) to Unix/OSX.

This only applies to new documents, so close any shell scripts which are open for editing in Notepad, then convert them in Linux to get rid of the extra line feeds. This can be done either using a sed command, or the dos2unix command. Not every distribution has the dos2unix command but sed is universal.

sed -i 's/\r\n/\n/g' <script>

This simple sed command searches for <linefeed><carriage return> (\r\n) and replaces it with a simple <carriage return> (\n).

The script can now be loaded back into notepad++ where it will work correctly.