-2

does anyone how does Linux decide which interpreter to call when running a text script? i need the detail, the purpose of the ‘shebang’ and how

1 Answers1

2

There are two main ways to execute an script:

  • Use the name of an executable that will load the script:

     perl script.pl
    

    python script.py

In that case, the shell loads the executable perl, python and gives it the arguments, the executable should be able to know that the given argument is an script and to load and execute it.

There is no especial magic here, the shell starts an executable with arguments.

  • The script is executable and is started by itself:

    $ script.sh  
    $ ./script.pl  
    $ /some/path/script.py
    

The control is given to the kernel by calling execve. If the script is a text file that has a valid she-bang (or an executable like ELF, for example) the kernel will understand the magic value at the start of the file and load the interpreter given. The interpreter, in turn, loads the text file as an script and executes it.

If the shell call to execve fails (the script doesn't have a valid she-bang, for example) the shell may load and execute the script directly. That is done by bash.

And, in some cases, from man bash:

If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell executes the specified interpreter on operating systems that do not handle this executable format themselves.

If you want more detail visit:

The #! magic, details about the shebang/hash-bang mechanism on various Unix flavours

Quite similar question

  • "...on operating systems that do not handle this executable format themselves." What does Bash do on Linux? Linux is mentioned in the title, and the question is tagged "linux". – Johan Myréen Jul 02 '20 at 19:14