How scripts without shebang are run

George Shuklin
OpsOps
Published in
1 min readFeb 25, 2021

This investigation risen from my explanation that shebang is processed by the kernel (in Linux). I was very proud of myself able to explain such obscure topic like exec formats. But there was an innocent question: what about scripts without shebang? How kernel knows what to use to run them?

I hadn’t known the answer. It took a little of strace to find it.

The answer

To get the answer I’ve made a simple ‘s’ script with +x flag but without shebang:

/bin/echo blabla

Then I’ve run strace -f sh and blindly typed ./s

Important part of the strace output

The trace was unexpectedly compact (just 3 screens), and the answer was almost obvious.

Shell (at least sh and bash) is trying to execute the script. Kernel trying to find signature (ELF, MZ for Wine, or shebang (#!) for scripts), and fails to do so. It rejects file with “Exec format error”.

Shell opens file and reads it (why?), and then execute it by itself with this script as an argument, basically reinventing shebang.

… this, actually, explains, why execve returns an error for non-shebanged scripts, and bash does not.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.