Linux shell scripting: /bin/sh : bad interpreter: No such file or directory
I usually get the below message when creating a Linux shell script with text editors like Notepad or Wordpad on Windows PC and executing it on Linux box:
“: /path/to/scriptfile:/bin/sh^M: bad interpreter: No such file or directory”
The top of the script is a line specifying the shell program by which the script is interpreted:
Double-check if there is any typo in the script file or the /bin/sh exists on the Linux machine. It sounds like everything is OK. Now, I am sure the error caused by the text editor used to create the script file. In fact, text editors of different platforms like Mac, PC, Linux can create text files with different formats and this is the reason of the error. In our case, line ending characters by the text editor on Windows are different from the ones on Linux which cause the shell scripted not be interpreted in a right way. To fix the error, do following steps at Linux command line:
- Open the script using vi program
- When file is opened, change the format of the script to the right one by entering
: set fileformat=unix
or just simply
: set ff=unix
- Finally, save the script for the new format taking effect and exit the vi program by entering
Now, the script is working fine without any error. An easy way this avoid this problem is creating scripts directly on Linux with vi program.
Please note that using text files of another operating system on Linux may result in similar problems. For example, some errors when compiling your source code files or a program can not read data text files. These problems can be solved using the solution in this post.