When running shell scripts, you may run into this bash error:
/bin/bash^M: bad interpreter: No such file or directory
This error occurs when the file you’re trying to execute contains DOS/Windows line endings. Unix uses just a line feed to end a line, but DOS actually uses a carriage return (^M) with a line feed for the same thing. When a Linux system encounters this it gets confused and thinks the script should be executed by /bin/bash^M which doesn’t exist.
To fix this Bash error, you just have to remove the carriage returns. There are a number of different ways to do this.
Your system may already have a small program named dos2unix that will easily convert a text file’s line endings. If you’re running Ubuntu, you can install it using apt-get.
# Ubuntu installation: sudo apt-get install dos2unix # to convert a file: dos2unix myscript.sh
vi and vim will convert line endings when you specify the file format.
Hit ESC to enter command mode where you can set the format and save your changes.
:set fileformat=unix :x!
sed is handy for cleaning up things like this from the command line.
sed -i 's/r//' myscript.sh
If you use Sublime Text you can convert your file by selecting Views > Line Endings > Unix. You may also want to set the default in your user preferences.