Wednesday, January 26, 2000

Control M Character [/bin/sh^M]

How to deal with ./configure : /bin/sh^M : bad interpreter ?

Windows and DOS terminate lines of text with CR (^M, or ASCII code 13) followed by LF (^J, or linefeed, ASCII code 10). Linux uses just LF, so the carriage returns appear as part of the text and are interpreted as such. That means they'll break scripts. 
Control-M(^M), an alternative way to do a carriage return in the ASCII character set.

We should understand a few things first:
CR = \r = Carriage Return
LF = \n = Line Feed

In DOS, all lines end with a CR/LF combination or \r\n.
In UNIX, all lines end with a single LF or \n.

The ^M that you are seeing is actually a CR or \r. If you want to test for carraige returns in a file, you want to look for \r. Try this on the file:
Code: od -c filename.txt

You'll see tabs, vertical tabs, carriage returns, linefeeds and whatnot using the slash notation. I find this to be the best method for determining what actual characters are in a file.
Or, if you just want to see the ^M notation, you can use cat, like so:
Code: cat -v filename.txt

To find whether a file has a CR or not you can use grep, this should print the lines with a CR:
Code: $ grep '^M' file1 # Type <Ctr-v><Ctr-m> to get ^M and not a ^ and an M.

  1. If you want to remove the ^M characters, you can use dos2unix as suggested above, or the correct tr syntax: Code: $ tr -d '\r' < infile.txt > outfile.txt
  2. Open file in VI Editor
    1. then press ESC then 
    2. :set fileformat=unix then
    3. :x! or :wq! to save file
  3. os2unix configure to fix this, or open it in vi and use :%s/^M//g; to substitute them all (use CTRL+V, CTRL+M to get the ^M)
  4. Or if you want to do this with a script: sed -i 's/\r//' filename
    1. $ cat file_name.sh | tr -d '\r' > file_name.sh.new
  5. If you're on OS X, you can change line endings in XCode by opening the file and selecting the [View -> Text -> Line Endings -> Unix] menu item, then Save. This is for XCode 3.x. Probably something similar in XCode 4.
  6. Download and install yourself a copy of Notepad++.
    1. Open your script file in Notepad++.
    2. File menu -> Save As ->
    3. Save as type: Unix script file (*.sh;*.bsh)
    4. Copy the new .sh file to your Linux system
    5. Maxe it executable with:  chmod 755 the_script_filename
    6. Run it with:  ./the_script_filename