Why Every Bash Script Starts with #! – Understanding the Shebang
This article explains what a shebang (#!) line is, why it’s used to specify a script interpreter, shows common examples, demonstrates how the kernel invokes the interpreter, and explores what happens when the shebang is omitted or points to unconventional commands.
What is a shebang?
The term shebang refers to the two characters # and ! that appear at the very first line of a script file. It tells the operating system which interpreter should execute the script.
How the kernel interprets the shebang
When the kernel loads an executable file that begins with #!, it reads the path that follows and launches that binary, passing the script file as the first argument. For example, #!/bin/bash causes the kernel to run /bin/bash script_name.
Common shebang lines
#!/bin/sh
#!/bin/bash
#!/usr/bin/perl
#!/usr/bin/tcl
#!/bin/sed -f
#!/usr/awk -fEach line specifies a different interpreter. The path after #! must exist and be executable; otherwise the script fails with an error such as “Command not found”.
Example script
Assume a file named shell_script contains only the shebang line: #!/bin/bash Make the file executable and run it:
chmod u+x shell_script
./shell_scriptThe kernel actually executes /bin/bash shell_script, so any commands in the file are interpreted by Bash.
Behavior when the shebang is omitted
If a script lacks a shebang, the kernel falls back to the current user's default shell. On many systems this is /bin/zsh or /bin/bash:
echo $0
/bin/zshThus the script runs under that interpreter.
Shebang can point to any executable
The interpreter does not have to be a shell; any executable can be used. For example, replacing the shebang with #!/bin/cat makes the script run the cat command, which simply outputs the script’s contents:
#!/bin/cat
hello worldRunning the script prints “hello world” (and the script itself) because cat reads the file and writes it to standard output.
Portability note
Using #!/bin/sh invokes the system’s default POSIX‑compatible shell. On most Linux distributions this is Bash, but on other UNIX variants it may be a different shell. Selecting /bin/sh improves portability at the cost of Bash‑specific extensions.
References
https://blog.twentytwotabs.com/the-smallest-bash-program-in-the-universe/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
dbaplus Community
Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
