Linux bin bash bad interpreter

Fix: “Not able to execute a .sh file: /bin/bash^M: bad interpreter”

Bash scripting is an essential part of Linux OS as it is mainly used to automate various tasks on the system. While executing a bash script, you might face an error stating, “Not able to execute a .sh file: /bin/bash^M: bad interpreter?”. The message “^M” is a control character representing a carriage return in Windows that the Linux operating system does not recognize. Let’s dive into more details.

This post will list the reasons and the solutions to fix the error. “Not able to execute a .sh file: /bin/bash.”

  • Reason 1: Script Transferred from Windows to Linux
  • Solution 1: Install Utility dos2unix
  • Solution 2: Removing the Carriage Return using the sed Command
  • Problem 2: Use of Incompatible Text Editor
  • Solution: Use indicators like Vim and nano

Reason 1: Script Transferred From Windows to Linux

The most common cause is that the script file was created on a Windows system and transferred to a Linux system without proper conversion. This can result in the Windows carriage return characters being present in the script file, causing the error message.

Solution 1: Install Utility dos2unix

To resolve this error, you can install a Linux utility named “dos2unix”, which converts the Windows-based file to Linux format. The Windows-based file uses carriage return and line feed to break a line, whereas in Linux is represented by the line feed only. So, the additional carriage return is usually responsible for causing this error that can be removed using this utility by installing it first:

$ sudo apt install dos2unix #For Ubuntu $ sudo yum install dos2unix #For CentOS $ sudo dnf install dos2unix #For Fedora

After installing this utility, all you need to do is to run the command mentioned below, which will help you resolve your error:

In the above file, bashfile.sh is the file name containing that error.

Solution 2: Removing the Carriage Return Using the sed Command

There is another command that can also be used to remove the carriage return, which is mentioned below:

-i: This option is used to edit a file.

-e: tells sed to use the following string as a script to execute.

Читайте также:  Настройка ssh git linux

‘s/\r$//’: which is a regular expression that matches the Windows carriage return character at the end of a line (\r$) and then deletes it from bashfile.sh.

After that, you should try again running the bash script, which should work now:

Reason 2: Use of Incompatible Text Editor

Another cause of this error message is that the script file was edited using a text editor that does not properly handle Linux line endings, such as Notepad. This can result in the line endings being changed from Unix line feed characters to Windows carriage return characters.

Solution: Use Editors Like Vim and nano

Another solution is to use a text editor capable of properly handling Linux line endings. Some popular text editors that can do many are Vim and Nano.

Conclusion

The error message “Not able to execute a .sh file: /bin/bash^M: bad interpreter” is caused by a problem with the line endings in the script file. This error message can be resolved by using dos2unix or by using a text editor that is capable of properly handling Unix line endings.

Following the solutions provided in this article, you can resolve the error message and successfully execute your script files on your Linux system.

Источник

Ошибка /bin/bash^M: bad interpreter: No such file or directory при запуске скриптов

Ошибка /bin/bashM: bad interpreter: No such file or directory при запуске скриптов

Как видно из текста ошибки, при запуске скрипта вместо стандартного шелла /bin/bash скрипт пытается запустить его из директории /bin/bash^M и ожидаемо выдает ошибку, потому что такого пути не существует. Все дело в том, что ^M — это символ возврата каретки (окончания строки), который обычно используется на Windows системах. По всей видимости, данный скрипт редактировался каким-либо текстовым редактором, в настройках которого был выставлен режим Windows (а не Linux) и из-за этого, при запуске скрипта получается такая ошибка.

Как исправить ошибку (способ 1: очень быстрый)

Допустим, наш скрипт, при запуске которого мы получаем ошибку будет называться script.sh .
1) Делаем его резервную копию, чтобы иметь возможность восстановить работоспособность, если что-либо пойдет не так.
2) Запускаем следующую команду:

Она должна заменить все символы переноса строки Windows на те, которые используются на Linux системах. Способ не совсем универсальный, поэтому иногда может не сработать.
3) После выполнения данной команды, пытаемся запустить на скрипт script.sh и проверить работоспособность. Если не помогло, то восстанавливаем оригинал из резервной копии и переходим ко второму способу.

Как исправить ошибку (способ 2: медленный, но очень надежный)

Если первый способ не помог, либо если вы часто сталкиваетесь с такой ошибкой, то можно воспользоваться специальной утилитой dos2unix , которая как раз подходит для таких случаев
1) Делаем резервную копию script.sh , чтобы восстановить его в случае проблем.
2) Устанавливаем утилиту dos2unix

sudo apt update && sudo apt install dos2unix
dos2unix script.sh dos2unix: converting file script.sh to Unix format. 

4) После выполнения данной команды, пытаемся запустить на скрипт script.sh и проверить работоспособность.

Читайте также:  Linux узнать какие диски примонтированы

Источник

Resolve Issue: Bin/Bash^M: Bad Interpreter: No Such File Or Directory

While working on different operating system platforms, we encountered a bundle of errors, i.e., performing some coding or installation. When we work in bash, we may encounter hundreds of bash related-errors. You could believe there is a permissions problem and attempt executing the chmod 777 instruction to give the bash script file all rights, but it will not solve the problem. It Is initiated by the carriage return “M”. The line feed symbol is used in Linux to indicate the finish of a line; meanwhile, the two-character combination CR LF is used in Windows. Your document has Windows line ends, which causes Linux to be perplexed. Let’s see the solutions for it.

In this tutorial, we will look at how to fix the problem that occurs while running bash or.sh file on a Linux environment. The poor interpreter is another name for this error. You might believe this is a permissions constraint and try using the chmod +x command to grant the shell script file all the required privileges, but this will not resolve the issue. The script specifies that it would be run using the “/bin/bash^M” shell. There is no such file; instead, “/bin/bash” is used. The “^M” character stands for carriage return.

The line feeding character is often used in Linux to indicate the ending of a line, whereas the two-character sequence CR/LF is often used in Windows-like operating systems. The file contains Windows line endings markers, which causes Linux to be perplexed. In a bash script file, how can I see CR or LF encoding characters? You may also view the line end characters as LFCR or LFCR by View → Show Symbol → Show End of Line. An example of a file with CR or LF characters is shown below:

The above and below displays are not available in the basic notepad editor; instead, you must install Notepad++, an advanced version of notepad. To fix the error in the Windows operating system, open the bash script file in the Notepad++ editor and then go to the preferences tab via the settings menu as below. Close the window after choosing Unix/OSX as the format. Afterwards, save and close the file.

Preferences → New Document/Default Directory Tab → Setting → Preferences → New Document/Default Directory Tab → Chose New Document Format →

Using Stream Editor Command

In UNIX, the SED command accounts for a line-by-line editor, and it can perform a wide range of file procedures such as scanning or searching, finding and replacing, inserting, and deleting. The SED command is most commonly used in UNIX and Linux-like operating systems for substituting or finding and replacing. Delete the CR characters that aren’t supposed to be there. You can use (sed) the command below in the image to accomplish this task:

Читайте также:  Linux sendmail send file

By Using Dos2UNIX Utility

Dos2Unix is a Programme that converts DOS to UNIX. To resolve the shell script for the Unix-Linux like operating systems, install the dos2unix utility and then run the dos2unix command given below:

If you get the command not found error, first install the dos2unix utility by running the command below from a Linux command line shell:

You can use the unix2dos command to convert the file back to DOS format.

In a bash script file, how can I view CR LF characters? Attempt file, file -k, and finally dos2unix -ih command as in below screen: Attempt file, file -k, and finally dos2unix -ih command as in below screen. For the Linux/Unix line “CR,” it simply prints text.

You may install it on macOS operating system using Homebrew as follows:

Then do the execute the below command to convert the file in dos format to UNIX format:

What Is The Purpose Of The Command dos2unix

DOS2UNIX is a utility that translates DOS line endings CR (carriage return) +LF (line feed) to UNIX line encodings in text files LF (line feed). It can also convert between UTF-16 and UTF-8 characters. You can translate from UNIX to DOS while utilizing the unix2dos command. Expectantly, this will resolve the problem you were having.

By Using Vim Editor

If you don’t have the DOS2UNIX Utility installed on your LINUX operating system, you might use the VIM editor to transform your shell script’s format to UNIX. Use the succeeding instruction to open the file in VIM Editor:

vi FILENAME.sh

vim FILENAME.sh

If you’re not in the current directory or folder where your bash file script is located, type the directory’s full path, as I did. But if you are in the same directory or folder, you can run the command directly as given above. VIM is a progressive form of the VI editor. Both VI and VIM commands do the same work. Run the command underneath to change the file format to the UNIX operating system:

Then, using the commands below, all changes are saved and close the file in the editor, write the file, and close it. Now you’re done. You can convert the format of your shell script to UNIX through any of the approaches described previously. We hope the above information helped resolve your problem.

Conclusion

This is all about the use of simple methods to resolve the issue “bin/bash^M: bad interpreter: No such file or directory”. All the examples used here are simple and easy to implement. We hope that you like it and learn more from it.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Оцените статью
Adblock
detector