Issue
I am trying to learn shell on Linux, but I've got a problem which seems confusing.
- My environment is:
- The problem is:
- I created a file named
foo
, and echoed#\!/bin/sh
to it, and the permission of filefoo
has been modified to100
by usingchmod
. - The file
foo
doesn't have the read or write permission indeed, that's for true, - but when I executed the command
./foo
, I got the error/bin/sh: ./foo: permission denied
.
- I created a file named
So why the Shell knows what the shebang in the file foo
is without the read permission ???
If anyone of you can proide any suggesstions, I will be really thankful !
Solution
So why the Shell knows what the shebang in the file foo is without the read permission ???
It is not the shell that reads the shebang line but the OS/kernel.
A shell script can be executed in the same way as a compiled program. The process uses a function of the exec*
family and passes ./foo
as the program to execute. These functions are based on system calls.
The OS/kernel then detects if the file is a compiled program which can be executed directly or a script file which must be passed to an interpreter. If the file contains a shebang line, the OS will execute the specified interpreter, which does not have to be a shell, otherwise it will run the default shell. The script file is passed as an argument to the interpreter.
The shell is running with normal user permissions and will get an error when it tries to open the script file.
You can find some information about executiong scripts in the POSIX specification of the exec
function family or in the Linux manual page for execve
. Search for the word interpreter. You could check the Linux kernel source code for more details.
Answered By - Bodo Answer Checked By - Mary Flores (WPSolving Volunteer)