1

For example, if I do

[OP@localhost executable]$ cat garbage 
lalala
trololol
[OP@localhost executable]$ chmod +x garbage
[OP@localhost executable]$ ./garbage 
./garbage: line 1: lalala: command not found
./garbage: line 2: trololol: command not found

Bash seems to be trying to interpret this "executable" as a script. However, there are two instances where this clearly does not happen: when the file begins with a #!, and ELF files. Are there any more? Is there a comprehensive documentation of this somewhere?

5
  • You can add pretty much anything as an executable using binfmt – muru Apr 11 '19 at 2:16
  • 1
    Not only bash does that, but any program which is trying to run an executable file via execvp(2) or execlp(2) (eg. try xargs <garbage ./garbage). That's required by the POSIX standard. – mosvy Apr 11 '19 at 2:22
  • In addition to what @mosvy says, IIRC the difference is that other programs try to run it using sh, but bash tries to run it itself irrespective of what sh is. (compare a script with echo $BASH_VERSION $_, ran with bash -c ./foo.sh, dash -c ./foo.sh and echo foo | xargs ./foo.sh – muru Apr 11 '19 at 2:33
  • 1
    Also a sequence of interesting Tim questions around this one. – Michael Homer Apr 11 '19 at 3:13
6

Expanding on my previous comment on another answer, the kernel contains seven binary loaders (look for files starting with binfmt_ there, or read the binfmt-specific Kconfig):

These are what determine the types of executable files that the kernel can execute. binfmt_misc in particular allows many other binaries to be handled by the kernel (at least, from the perspective of the process calling one of the exec functions).

However this doesn’t cover the whole story, since the C library and shells themselves are also involved. POSIX now requires that the execlp and execvp functions, when they encounter an executable which the kernel can’t run, try running it using a shell; see the rationale here for details.

The way all this interacts to provide the behaviour you’re seeing is detailed in What exactly happens when I execute a file in my shell? and Which shell interpreter runs a script with no shebang?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.