11

I just shifted from Windows to Linux (Ubuntu 18.04)...and following a tutorial to learn bash scripting...

I wrote a simple shell script

#!bin/bash 

echo "Hello World" 

but when I tried to run it using

$ ./test1.sh

it throws an error

bash: ./test1.sh: bin/bash: bad interpreter: No such file or directory

When I am running it using

$ bash test1.sh

it runs fine

I tried searching it and found many answers but all covers errors due to some difference between windows newline ^M and ubuntu newline...I tried opening it in VIM under binary mode(don't know what it is) but it did'not have any ^M tag after bin/bash.

Please suggest what I am doing wrong.

Melebius
  • 11,431
  • 9
  • 52
  • 78

3 Answers3

21

You’re missing a leading slash making the shebang an absolute path:

#!/bin/bash
# ↑ here

In your case, the shell seems to be searching for ./bin/bash.

The shebang (and also executable permission) is only taken into account if you’re running the script as a program:

$ ./test1.sh

It is ignored if you directly run the interpreter and provide your script as an argument:

$ bash test1.sh

See also: https://askubuntu.com/a/850387/250300

Melebius
  • 11,431
  • 9
  • 52
  • 78
6

Although this is an old question, since there is no explanation towards the ^M problem, maybe it's useful:

  • ^M comes from the difference between "Windows" return and Linux return.
  • Simplest solution is to use an editor to convert all the return in your script from CRLF (Win) to LF (Linux), e.g. VS Code.
0

Sorry for reviving old topic but I had the same issue and managed to fix it, not sure what exactly helped but did all the things listed below. First of all install Gedit through the command:

sudo apt-get install gedit

Then make sure that you saved the script with Unix/Linux line ending. After this, type in terminal, while being in the proper folder:

chmod +x filename

The last thing is replacing in script itself

#!bin/bash 

with

#!/bin/bash 
Kamila
  • 1