Advertisement
Advertisement


Bash script and /bin/bash^M: bad interpreter: No such file or directory


Question

I'm learning through this tutorial to learn bash scripts to automate a few tasks for me. I'm connecting to a server using putty.

The script, located in .../Documents/LOG, is:

#!/bin/bash
# My first script
echo "Hello World!"

And I executed the following for read/write/execute permissions

chmod 755 my_script

Then, when I enter ./my_script, I'm getting the error given in the title.

Some similar questions wanted to see these, so I think they might help:

which bash

/bin/bash

and

echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/bin/mh

I tried adding current directory to PATH, but that doesn't work..

2020/04/05
1
440
4/5/2020 11:38:28 AM

Accepted Answer

I have seen this issue when creating scripts in Windows env and then porting over to run on a Unix environment.

Try running dos2unix on the script:

http://dos2unix.sourceforge.net/

Or just rewrite the script in your Unix env using vi and test.

Unix uses different line endings so can't read the file you created on Windows. Hence it is seeing ^M as an illegal character.

If you want to write a file on Windows and then port over, make sure your editor is set to create files in UNIX format.

In notepad++ in the bottom right of the screen, it tells you the document format. By default, it will say Dos\Windows. To change it go to

  • settings->preferences
  • new document / default directory tab
  • select the format as unix and close
  • create a new document
2018/10/04
591
10/4/2018 9:09:41 AM


If you use Sublime Text on Windows or Mac to edit your scripts:

Click on View > Line Endings > Unix and save the file again.

enter image description here

2016/09/15

This is caused by editing file in windows and importing and executing in unix.

dos2unix -k -o filename should do the trick.

2013/08/13

In notepad++ you can set it for the file specifically by pressing

Edit --> EOL Conversion --> UNIX/OSX Format

enter image description here

2014/06/25

problem is with dos line ending. Following will convert it for unix

dos2unix file_name

NB: you may need to install dos2unix first with yum install dos2unix

another way to do it is using sed command to search and replace the dos line ending characters to unix format:

$sed -i -e 's/\r$//' your_script.sh
2016/09/29

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/\r$//' setup.sh
2016/05/19