Sometimes shell scripts in Linux give this error:

bash: ./t1.sh: /bin/sh^M: bad interpreter: No such file or directory

This happens when files are transferred from a Windows machine to a Linux machine. Different operating systems use different line ending characters:

OSLine EndCharacter
UNIX/LinuxLF\n
DOS/WindowsCRLF\r and \n
MacCR\r

CR (Carriage Return): Return cursor to left margin, Ctrl-M (^M) or hex 0D LF (Linefeed): Move cursor down, Ctrl-J (^J) or hex 0A

Solution Link to heading

  1. Create a shell script with ^M characters at line ends:
#!/bin/sh^M$
^M$
ls -l^M$
  1. Make executable and run -- it fails:
chmod +x bad_int.sh
./bad_int.sh
# bash: ./bad_int.sh: /bin/sh^M: bad interpreter: No such file or directory
  1. Use cat -A to see non-printable characters:
cat -A bad_int.sh
# #!/bin/sh^M$
# ^M$
# ls -l^M$
  1. Remove all ^M characters using cat and sed:
cat -A bad_int.sh | sed -e 's/\^M\$//g' > bad_int_solved.sh
chmod +x bad_int_solved.sh
./bad_int_solved.sh
# (script runs correctly)

Originally published May 16, 2010 on jaymspatel.blogspot.com