0

I wrote simple file "hello world" and try to execute it on virtual server by SSH.

#!/bin/bash
echo "Hello world"

Of course I give chmod +x

Then on one server I try to execute it by command:

./file.sh

And I have reply:

-bash: ./file.sh: Permission denied

Works only when I start it by command:

sh file.sh

On other server both commands works fine...

So my question is: is there any kind of permission that prevents execution with ./ command?

What is the difference between the two commands?

  • What shell do you use? What is the output of /bin/bash file.sh? – Kamil Maciorowski May 12 '16 at 12:18
  • /bin/bash file.sh - works fine. I have this problem on zenbox.pl server – Max May 12 '16 at 12:34
2

The filesystem may be mounted with noexec. I recreated this in my Debian. The behavior fits.

When you run ./file.sh it is treated as executable; however with /bin/bash file.sh the executable is /bin/bash.

| improve this answer | |
1

This is an extract from the manual (man sh):-

If command line arguments besides the options have been specified, then the shell treats the first argument as the name of a file from which to read commands (a shell script), and the remaining arguments are set as the positional parameters of the shell ($1, $2, etc). Otherwise, the shell reads commands from its standard input.

Thus in sh file.sh the specified file file.sh becomes an input source for the shell, so needs to be readable, but need not be executable. The same is true of the source or . command, so the following will all run a non-executable file:-

sh ./file.sh
sh<./file.sh
. ./file.sh
source ./file.sh

The last two will execute in the current shell, the first two in a sub-shell. Note that sh -c ./file.sh will require file.sh to executable, while sh -c ". ./file.sh" needn't. Note also that if file.sh is executable, then its location needs to be in $PATH if it is called directly, unless a specific path (./ in the example) is included:

file.sh

However, the four previous examples do not need the ./ prefix, as the file to read will always be sought in the current directory (though the . and source commands will also search $PATH).

Two final points:-

  1. The four examples work only for script files: they will all fail if file.sh is a binary executable.
  2. In the four examples, the #!/bin/bash comment is just a comment: the executing sh will read it as such and will not clone bash to execute the rest of the file, so any bash extensions in it will cause errors.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.