Terminal · intermediate

Shell script and shebang

A shell script is a text file containing shell-language commands, and an executable script's initial #! line asks the operating system to launch a specified interpreter with that file.

Why it matters

Declaring the intended interpreter prevents a script from being parsed by an incompatible shell and clarifies which language features are available.

Mental model

How to reason about shell script and shebang

Direct execution hands the script pathname to the kernel; when the file begins with #!, the kernel launches the named interpreter with an implementation-defined argument arrangement and the script path.

Analogy

The shebang is a routing label on a document that tells the operating system which trained reader should interpret its contents.

Examples

See the boundary, not just the happy path

Worked example · Portable POSIX shell script

#!/bin/sh
printf '%s\n' "ready"

The declared /bin/sh interpreter requires the body to use POSIX shell syntax rather than assuming Bash-only features.

Worked example · Resolve Bash through env

#!/usr/bin/env bash
printf '%(%F)T\n' -1

env searches PATH for bash, which helps installations with different Bash locations but makes interpreter choice depend on the execution environment's PATH.

Useful contrast · Explicit interpreter ignores direct-execution routing

bash script.sh

Here Bash reads script.sh because it was explicitly invoked; the kernel does not use the file's shebang to choose the interpreter.

Common mistakes

Misconceptions to remove early

Declaring sh while writing Bash syntax

Arrays, [[ ... ]], and other Bash features are not guaranteed in /bin/sh; declare Bash or write to the POSIX shell language.

Placing bytes before #!

For direct execution, #! must begin at the start of the file; a byte-order mark or earlier blank line can prevent interpreter recognition.

Quick check

Can you predict the result?

1. What does #!/bin/sh promise about the script body?
  • It should be valid for the system's /bin/sh implementation.
  • It is always parsed by the newest Bash.
  • It can use any shell's syntax interchangeably.
Answer: It should be valid for the system's /bin/sh implementation.
2. What tradeoff does #!/usr/bin/env bash make?
Answer: It locates Bash through PATH, improving location flexibility while making interpreter selection environment-dependent.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster