What is the shebang line and why is it important in shell scripts?
The shebang (#!/bin/bash) is the script's first line; it tells the kernel which interpreter to run the file with.
* How the kernel uses #! to pick the interpreter when you run a script. *
When you execute a script directly (./script.sh), the kernel reads the first two bytes. If they're #!, it runs the program named after them and feeds it the script. So #!/bin/bash means "run this file through /bin/bash." Without a shebang, the file is handed to whatever shell happens to be calling it — which may not be bash, so bash-specific syntax (arrays, [[ ]]) can mysteriously break.
Format:
#!/bin/bash
# Your script starts here
echo "Hello World"
Key points:
- Must be the very first line (no spaces before
#!) #!followed by the path to the interpreter- Without it, the script runs in the current shell (may behave differently)
Common shebangs:
| Shebang | Interpreter |
|---|---|
#!/bin/bash |
Bash shell |
#!/bin/sh |
Bourne shell (POSIX) |
#!/usr/bin/python3 |
Python 3 |
#!/usr/bin/env bash |
Bash (portable) |
Tip: Use #!/usr/bin/env bash for portability - it finds bash in the user's PATH.
Go deeper:
Shebang (Unix) — Wikipedia — the
#!interpreter directive's kernel mechanics, including theenvportability trick.