How to Fix "/bin/sh^M: bad interpreter: No such file or directory"
Let’s see how we can fix the /bin/sh^M: bad interpreter: No such file or directory
error when running a Windows script in Linux.
1. Encountering the bad interpreter
Suppose we tried running this run.sh
shell script below.
#!/bin/sh
echo "Hello!"
Maybe we ran the following command:
./run.sh
And encountered this error:
./run.sh: bad interpreter: /bin/sh^M: no such file or directory
2. Fixing Windows line endings (carriage returns)
This issue occurs most commonly when Linux tries to read a script created in Windows.
When a script is created in a Windows environment, Windows will add carriage returns and new lines to the end of each line, which confuses Linux.
We’ll want to remove the carriage returns using sed
(stream edit command).
Let’s run the sed
command below.
sed -i -e 's/\r$//' run.sh
If you can’t overwrite the script, you can redirect the output to a new script.
cat run.sh | sed -e 's/\r$//' > new_run.sh
Now, try running run.sh
again.
./run.sh