Search code examples
linuxbashcentosshebang

Bash script doesn't work without shebang BUT the shebang results in an error message


I am trying to run a bash script in CentOS 6. It doesn't work without a shebang header. When I include the shebang, however, it displays an error message!

Here's a script called test.sh. I have it in my $HOME/bin directory. I ran chmod 777 on it to eliminate any permissions issues. I verified it is using Unix line endings...

test_var=test
echo $test_var

I am executing like this:

sh ~/bin/test.sh

I get the following result from that:

/home/myusername/bin/test.sh: line 1: test_var=test: command not found

Now I add a shebang, so the script becomes:

#!/bin/bash
test_var=test
echo $test_var

When I run that, I get:

/home/myusername/bin/test.sh: line 1: #!/bin/bash: No such file or directory
test

So it didn't have a problem assigning the variable once the shebang was added, but it doesn't like the shebang at the same time!

I checked and /bin/bash does in fact exist. I tried a collection of other shebangs and got the same results. I even tried something overtly invalid, i.e. #!/fake/path, and the result is the same!

The script won't run without a shebang added (no matter what it is), and yet it complains about the shebang (no matter what it is)!


Solution

  • You have an encoding problem.

    Look at: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8

    A text editor or web browser misinterpreting the text as ISO-8859-1 or CP1252 will display the characters  for this.

    Save your file as UTF-8 without BOM or use system editor (vi, ...)