Whether you are a first time linux user or a 15 year veteran, you have, or eventually will run into this issue. /bin/bash^M: bad interpreter. Trying to launch a shell script and this error happens. What is it? Why are you getting it? And of course, you must curse linux a few times.
Linux error: /bin/bash^M: bad interpreter: No such file or directory
I came across this issue when I was working on a shell script for an Autoscaling EC2 setup using Amazon Web Services (AWS). In the script, I was to specify the startup parameters of the application server. I made the mistake by taking the file on a windows system, then copying it back to linux. The worse part? The file was working fine, until I brought it into Windows. But, my comfort was windows, and so I decided to go down that path.
Time to move on to a few things to try to fix this issue: /bin/bash^M: bad interpreter: No such file or directory
The first and foremost thing you can do, is to check the permissions of the file. So run your chmod 777 for now. Did it work? No? Of course not. You still get that darn error: /bin/bash^M: bad interpreter: No such file or directory
Let’s look at that error again in detail
That ^M is actually a carriage return character.
Windows to Linux and Linux to Windows
What I learned is that this error is VERY common when you try to copy paste code from windows and linux. Or, even if you try to edit a linux file in windows.
Let’s move on to the fix
The sed Command
sed -i -e 's/\r$//' FILE-NAME.sh
The sed command can be used, and replace FILE-NAME with the name of your file. I had great success running this command when I took a file from linux to windows, made my changes in Notepad, then attempted to paste that back into the linux file.
Problem solved! no more /bin/bash^M: bad interpreter: No such file or directory
There is a program called dos2unix that fixes shell scripts.
Install the program using this command
sudo apt-get install dos2unix
Run the program using this command
Running this program is also another option.
Lessons learned is switching from linux to windows sounds easy for editing files, but in reality can set you down a 1 hour delay in trying to find out what happened. I commonly take files from linux and modify them in windows, like the .htaccess, robots.txt or even straight php and html files. bash sh scripts just need a little more steps. Hopefully the issue with /bin/bash^M: bad interpreter: No such file or directory is finally solved for you.