Problem with command not found ^M:
The other day I was trying to execute this simple shell script. The shell script was using Z shell. when I tried to execute the shell script, it threw me the following error:
script.sh:2: command not found: ^M
script.sh:4: parse error near `then^M’
After digging a little bit in to the problem, I found that this character ^M represents an extra useless space. But this was the weird part. There were many spaces in the shell file but it was quite common and most certainly not useless. Even if I tried removing the “troublesome” extra space, it keep on throwing the same error for some other extra space.
Reason:
The reason which was causing this error was that I had used Windows explorer to write the shell script. What I meant that I had my Linux network drive mounted in Windows. I wrote the shell scripting in Windows, saved it as .sh file and tried executing it. And that is where it went wrong.
You see, when I used Windows to write the program, it saved it in Windows format. And this is why Linux could not encode it properly. A simple file command showed the “true color” of this “traitor Windows” file.
Solution:
Simple most solution to get rid of this error is to convert the Windows file to Unix (read Linux) format. dos2unix tool comes handy in this case. It comes pre-installed in many Linux systems. Here is how to use it:
dos2unix script.sh
where script.sh could be your shell script file name.
The output of the command may look like this:
dos2unix: converting file script.sh to UNIX format …
That is it. No need to do anything further. The next time you execute your shell script, it will not show the ^M command not found error. Cheers