Shell script error - bad interpreter - No such file or directory

Unix/Linux FAQ: How do I solve the problem of the “bad interpreter” error message?

Sometimes when you take a file from a DOS/Windows system and move it to a Linux or Unix system you’ll have problems with the dreaded ^M character. This happened recently when I moved an Ant script from a Windows system to my Mac OS X system. When I tried to run the shell script under the Mac Terminal I got this “bad interpreter” error message:

: bad interpreter: No such file or directory

I couldn’t figure out what the message meant at first, but finally it hit me: the dreaded ^M problem. Sure enough, I opened the file in the vim editor with the -b (binary), like this:

vi -b myfile.sh

Opening the file in vi/vim with the “binary” switch (-b), I saw the extra ^M at the end of each line. I then issued one of my favorite vi commands to remove all these ^M characters, and the script magically began working. Here’s that magic vi command:

:1,$s/^M//g

Note that you don’t really type a ^ character and then a M character to generate that command. You actually type [Control][v] and then [Control][m] to create the necessary character. I don’t know the genesis of this, but if you'll type those two keystrokes I think you’ll see that it works as described.