The linked page in your other response only has this reference to the shebang line
It's a little bit hidden in 2.9.1 Simple Commands, Command Search and Execution, number 2:
If the command name contains at least one <slash>, the shell shall execute the utility in a separate utility environment with actions equivalent to calling the execl() function defined in the System Interfaces volume of POSIX.1-2017 with the path and arg0 arguments set to the command name, and the remaining execl() arguments set to the command arguments (if any) and the null terminator.
If the execl() function fails due to an error equivalent to the [ENOEXEC] error, the shell shall execute a command equivalent to having a shell invoked with the command name as its first operand, with any remaining arguments passed to the new shell. If the executable file is not a text file, the shell may bypass this command execution. In this case, it shall write an error message and shall return an exit status of 126.
What happens here is this:
- The shell calls exec($script)
- The kernel reads the first few bytes of $script
- The kernel detects that $script starts with #!
- The kernel tries to execute the interpreter that follows #!, but fails.
- The kernel returns the ENOEXEC error to the shell (see POSIX exec)
- The shell now has to follow the case described above: create a new shell instance and pass it $script as the first argument.
The rationale for this is that ancient shell scripts did not have a #! line. More details ...
Demo:
/tmp>echo 'echo Hello from the shell' > demo
/tmp>chmod +x demo
/tmp>./demo
Hello from the shell
/tmp>echo '#!/no/such/exe' > demo
/tmp>echo 'echo Hello from the shell' >> demo
/tmp>chmod +x demo
/tmp>./demo
-bash: ./demo: /no/such/exe: bad interpreter: No such file or director
+y
/tmp>chmod -x demo
/tmp>./demo
-bash: ./demo: Permission denied
/tmp>
Note that in the second attempt to run demo, my login shell (indicated by the leading "-") complains about the demo script specifying a bad interpreter. In the third attempt, it complains about wrong permissions on the script.
And now, the non-obvious trick: I copied an old DOS executable (defrag.exe) to /tmp.
/tmp>echo '#!/tmp/defrag.exe' > demo
/tmp>echo 'echo Hello from the shell' >> demo
/tmp>chmod +x demo
/tmp>./demo
-bash: ./demo: /tmp/defrag.exe: bad interpreter: Permission denied
/tmp>chmod +x defrag.exe
/tmp>./demo
Hello from the shell
/tmp>./defrag.exe
-bash: ./defrag.exe: cannot execute binary file: Exec format error
/tmp>
No, my Linux did not execute defrag.exe. It can't, I don't have any emulator or the like set up for DOS executables. Bash complains if defrag.exe is not executable, but when it is executable and the kernel still had complained about an unknown executable behind the scenes, the little demo script is executed as a shell script.
Alexander
--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
|