How to resolve error : ‘\r’: command not found’ in linux / How to change end of line character on Windows to Unix

If you create a shell script file on windows and copy it on linux for execution, you might get below error

$’\r’: command not found

This is because end of line character on windows is different than that on linux. End of line on windows is a combination of Carriage return and Line Feed characters(CR + LF) while that on linux is only Line Feed(LF).
Thus, a script created on windows when executed on linux gives the above error.
Solution
There are 2 ways in which this problem can be solved.
Method 1: Using dos2unix utility
Install dos2unix program on the target linux system if it is not already present and convert the script from windows to linux format.
It can be executed using below syntax

dos2unix <file name>

Example,

dos2unix script.sh

This command will remove all Carriage Return(CR) characters from the file. If you do not want to modify the original file, you can also convert the file and save it to a different file using the below command,

dos2unix -n script.sh updated.sh

For installing dos2unix program on linux system, use the below command

sudo apt-get install dos2unix

Method 2: Using sed command in linux
sed command is a stream editor which is used for manipulating files such as deleting words or lines, replacing its content with some other words, inserting content into the file etc.
This command can be used to remove the CR characters from a file and its syntax is

sed -i ‘s/\r$//’ <name of file>

where -i is for in place editing means it modifies the original file, s is for substitution operation and the rest of the command removes ‘\r’ characters from the end of all the lines from the supplied file.
In case you do not want to lose the original contents of the file, use the below command

sed -i.bak ‘s/\r$//’ <name of file>

This command will create a backup of the original file with a .bak extension. Thus, below command

sed -i.bak ‘s/\r$//’ script.sh

will remove '\r' characters from the file and will create a file script.sh.bak with original file contents in the same location.
Hope this post takes you out of this problem. Hit the clap below to agree.

Leave a Reply