Sunday, September 4, 2022

[SOLVED] Why the shell knows the interpreter specified in the shebang-line of a file without read permission

Issue

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


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)