Fun and games with carriage returns in bash scripts in Windows Terminal

Recently, I was trying to run a bash script in my Windows terminal, and ran into an error I haven’t seen for quite some time:

./deploy.sh: line 5: $’\r’: command not found
./deploy.sh: line 9: $’\r’: command not found
./deploy.sh: line 15: $’\r’: command not found
./deploy.sh: line 19: $’\r’: command not found
./deploy.sh: line 21: $’\r’: command not found

These lines are actually blank in the script, and I recognized the \r as a carriage return. Also, even though these lines are generating error messages, I know from experience that the other lines won’t be interpreted properly either.

The issue is the way that Unix and Windows handle carriage returns differently. Windows uses a carriage return and line feed (“\r\n”) as a line ending, while Unix uses just a line feed (“\n”). In this case, even though I’m running the script on a Windows machines, the processor is Unix, so the line feeds need to be fixed before the script will run in terminal.

StackOverflow to the rescue — hat tip to StackOverflow user Michael P Bazos for sorting out the fussy formatting of this sed command to remove all extra \rs….:

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

A quick save and I’m back to my deployment!

I’m sure you will, as I do, back up your script before running any sed -i command, which enables in-place editing of your file.

If this tip helps you as much as it helped me, please share a clap!

Leave a Reply