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:
| OS | Line End | Character |
|---|---|---|
| UNIX/Linux | LF | \n |
| DOS/Windows | CRLF | \r and \n |
| Mac | CR | \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
- Create a shell script with ^M characters at line ends:
#!/bin/sh^M$
^M$
ls -l^M$
- 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
- Use
cat -Ato see non-printable characters:
cat -A bad_int.sh
# #!/bin/sh^M$
# ^M$
# ls -l^M$
- Remove all ^M characters using
catandsed:
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