Home > database >  Why the shell knows the interpreter specified in the shebang-line of a file without read permission
Why the shell knows the interpreter specified in the shebang-line of a file without read permission

Time:05-23

I am trying to learn shell on Linux, but I've got a problem which seems confusing.

  • My environment is:
    • OS: Manjaro 21.2.6 Qonos
    • Kernel: x86_64 Linux 5.15.38-1-MANJARO
    • Shell: zsh 5.8.1 (x86_64-pc-linux-gnu)
  • The problem is:
    • I created a file named foo, and echoed #\!/bin/sh to it, and the permission of file foo has been modified to 100 by using chmod.
    • 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.

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 !

behavior-example

CodePudding user response:

You get this error because the script itself do not have execution or read permission. To run script in shell (on your way) you need to have read and execute permissions:

chmod 500 foo
./foo

the other way to run the script is:

sh foo

and you do not need execution permission in this case. For the record the standard way is to use construction like:

#!/bin/sh

You do not need to escape exclamation mark

CodePudding user response:

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.

  • Related