The Analogy: The Pathology Lab's Specimen Label
Tubes arrive at a hospital pathology lab in transport boxes from the wards. Each tube carries a printed label, and the porter who wheels the rack in from the loading bay never opens a tube and never judges a sample. They read the top line of the label, which names the analyser the tube must go on, and they walk it to that bay. Two entirely separate things are checked at the door: the analyser named on the label, and the requesting clinician's authorisation stamp in the corner. Either can be wrong on its own.
The analyser name comes in two styles, and labs argue about which is better. Some labels name a specific machine by its asset number, the one bolted into the corner of Bay 3. Others name a role -- "the haematology analyser" -- and the porter consults the board by the door to find out which machine currently holds that role. The asset number is exact and unambiguous, and it stops working the day the machine is replaced. The role follows the board, which means the tube goes onto whatever machine has been designated today, which is usually what you wanted and occasionally a surprise.
The authorisation stamp is independent of all that, and it can be missing while the label itself is perfect. An unstamped tube gets refused at the door even though every person in the corridor can read which analyser it is asking for. A tube whose label names a bay that no longer exists is refused too, and here the refusal slip is genuinely unhelpful: it names the tube, not the missing bay, so the note that comes back to the ward reads as though the tube itself were the problem.
The failure mode is quieter than either of those. The label printer on Ward 6 has been jamming and adds a stray invisible character to the end of the analyser name. That name now matches nothing on the board, and the refusal slip quotes the whole name including the character nobody can see, so it reads as though the lab has misplaced a machine that is standing in plain sight. And there is a second thing that fails to travel: the ward keeps its own local conventions -- preferred rack order, in-house shorthand, which tests get run together -- on a card pinned above its own bench, and that card does not go into the transport box. The lab applies its own house defaults instead. No refusal slip is issued at all. The results simply come back subtly different from what the ward expected, and it takes weeks for anyone to work out why.
Syntax or Core Structure
A shell script is an ordinary text file. Nothing about it is special until you decide how to start it, and there are three genuinely different ways to do that. The difference between them is not style; it decides which process runs the code and which variables survive afterwards.
#!/usr/bin/env bash
printf 'in $0 : %s\n' "$(basename "$0")"
printf 'in BASH_SOURCE : %s\n' "$(basename "${BASH_SOURCE[0]}")"
printf 'arguments : %d\n' "$#"
Save that as hello.sh, make it executable with chmod +x hello.sh, and start it three ways from a driver script:
#!/usr/bin/env bash
printf '== ./hello.sh one two\n'
./hello.sh one two
printf '== bash hello.sh one two\n'
bash hello.sh one two
printf '== source hello.sh one two\n'
source ./hello.sh one two
Output:
== ./hello.sh one two
in $0 : hello.sh
in BASH_SOURCE : hello.sh
arguments : 2
== bash hello.sh one two
in $0 : hello.sh
in BASH_SOURCE : hello.sh
arguments : 2
== source hello.sh one two
in $0 : driver.sh
in BASH_SOURCE : hello.sh
arguments : 2
The first two forms are nearly the same: a new bash process starts, $0 is the script's own name, and the shebang decides the interpreter in the first case while the command line decides it in the second. The third form is the interesting one. source does not start a process at all; it reads the file into the shell that is already running, which is why $0 is still driver.sh -- the caller's name -- while ${BASH_SOURCE[0]} correctly reports hello.sh. That distinction is the whole reason BASH_SOURCE exists, and it is why a library meant to be sourced must never use $0 to find itself.
The shebang itself has three rules and they are less flexible than they look:
#!/usr/bin/env bash
The #! must be the first two bytes of the file, with nothing before it -- not a blank line, not a comment, not a byte-order mark. What follows is a path to an interpreter, and it must be a path, not a command to be looked up. And on Linux everything after the interpreter path is passed as one single argument, however many words it looks like.
Technical Depth: What Happens Between Enter and Your First Line
The four ways that first line can read
| First line | How the interpreter is located | What it costs you |
|---|---|---|
#!/bin/bash | a fixed absolute path, no searching | breaks on any system that keeps bash elsewhere, and always picks the system's own bash |
#!/usr/bin/env bash | env searches PATH for the first bash | follows PATH, so it finds a newer bash installed alongside an ancient system one |
#!/bin/sh | a fixed path to whatever the system calls its POSIX shell | no bash features are guaranteed; on Debian and Ubuntu this is dash, not bash |
| no shebang at all | execve fails, and the calling shell runs the file | it works by accident and depends entirely on who invoked it |
The last row deserves more suspicion than it usually gets. When the kernel refuses a file that has no recognised header, the shell that tried to run it catches the failure and interprets the file itself. So a script with no shebang works perfectly when you test it from your bash prompt and fails the first time cron, a Makefile, or another program starts it with something else. The same applies to a shebang that is not on the first line: it becomes an ordinary comment and the accident takes over.
One interpreter argument, and how that bites
Everything after the interpreter path is handed over as a single argument on Linux. So #!/usr/bin/env bash -u asks env to run a program whose name is literally bash -u, spaces included:
#!/usr/bin/env bash -u
printf 'ran\n'
Output: (both lines on standard error; the script never runs and the exit status is 127)
/usr/bin/env: 'bash -u': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
GNU env is unusually helpful here and tells you the fix. -S makes env split the rest of the line itself:
#!/usr/bin/env -S bash -u
case $- in
*u*) printf 'nounset is on\n' ;;
*) printf 'nounset is off\n' ;;
esac
Output:
nounset is on
-S is a GNU extension, so a portable script puts set -u on its second line instead of trying to be clever on the first.
Two exit codes worth recognising on sight
| Status | Meaning | What usually caused it |
|---|---|---|
| 0 | the script ran and chose to succeed | -- |
| 126 | the file was found but could not be executed | the executable bit is missing, or the name is a directory |
| 127 | the command was not found | a typo, a directory missing from PATH, or a shebang naming an interpreter that is not installed |
That last cause is the one that wastes afternoons. If the shebang names a missing interpreter, the error message names your script, not the interpreter, so ./deploy.sh: No such file or directory appears for a file you are looking at in your editor. The three cases are easy to tell apart once you have seen the numbers:
#!/usr/bin/env bash
mkdir -p adir
bash -c './adir' 2>/dev/null; printf 'directory -> %d\n' "$?"
bash -c './nosuchthing' 2>/dev/null; printf 'missing -> %d\n' "$?"
bash -c 'nosuchcommand' 2>/dev/null; printf 'no command -> %d\n' "$?"
Output:
directory -> 126
missing -> 127
no command -> 127
The startup files a script does not read
This is the ward's pinned card that never gets into the transport box. Which files bash reads depends entirely on how it was started:
| How bash started | Files it reads |
|---|---|
| interactive login shell | /etc/profile, then the first that exists of ~/.bash_profile, ~/.bash_login, ~/.profile |
| interactive non-login shell | /etc/bash.bashrc where the distribution provides it, then ~/.bashrc |
| non-interactive shell, which is your script | none at all, unless BASH_ENV names a file |
invoked as sh | none at all, unless ENV names a file, and POSIX mode is on |
So your aliases, your functions, your PATH additions and your shopt settings are all absent inside a script, no matter how reliably they work when you type the same commands by hand. BASH_ENV is the one documented hook:
#!/usr/bin/env bash
printf 'GREETING is [%s]\n' "${GREETING-unset}"
Run it plainly, then with BASH_ENV=./fake.rc bash usesrc.sh where fake.rc contains GREETING="from the rc file":
Output:
GREETING is [unset]
GREETING is [from the rc file]
Aliases show the same rule from the other side. Alias expansion is switched off in non-interactive shells, so an alias defined inside a script does not work until you turn the feature on:
#!/usr/bin/env bash
alias hi='printf "hello from the alias\n"'
hi 2>/dev/null || printf 'alias not expanded, status %d\n' "$?"
shopt -s expand_aliases
alias ho='printf "hello from the second alias\n"'
ho
Output:
alias not expanded, status 127
hello from the second alias
Status 127 is the giveaway: the shell looked for a command called hi and found none. The practical conclusion is that scripts use functions, never aliases.
Finding your own directory
A script that needs a file next to it cannot use the current working directory, because the caller chooses that. It has to ask where it lives:
#!/usr/bin/env bash
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
printf 'directory holding the script : %s\n' "$(basename "$here")"
printf 'sibling data file readable : %s\n' "$([ -r "$here/data.txt" ] && echo yes || echo no)"
printf 'data first line : %s\n' "$(head -n1 "$here/data.txt")"
Run once from the parent directory and once from inside pkg itself:
Output:
directory holding the script : pkg
sibling data file readable : yes
data first line : plate widths in mm
directory holding the script : pkg
sibling data file readable : yes
data first line : plate widths in mm
dirname gives the directory part of the path the script was invoked by, cd into it makes that path absolute, and pwd reports the result. The -- guards against a path beginning with a hyphen. BASH_SOURCE rather than $0 means the same line keeps working if the file is later sourced instead of executed.
Real World Example: A Tool That Works From Anywhere, Executed or Sourced
Here is the shape almost every installed shell tool ends up with. It refuses to run under the wrong interpreter, works out where it lives, loads a configuration file that sits beside it, and behaves correctly whether it was executed as a program or sourced into an existing shell.
#!/usr/bin/env bash
set -u
if [ -z "${BASH_VERSION-}" ]; then
printf 'platectl: needs bash, not a POSIX sh\n' >&2
exit 1
fi
if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
printf 'platectl: needs bash 4 or newer\n' >&2
exit 1
fi
if [ "${BASH_SOURCE[0]}" = "$0" ]; then mode=executed; else mode=sourced; fi
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
conf=$here/plates.conf
if [ ! -r "$conf" ]; then
printf 'platectl: cannot read %s\n' "$(basename "$conf")" >&2
[ "$mode" = executed ] && exit 2 || return 2
fi
. "$conf"
steps=$(( (PLATE_MAX - PLATE_MIN) / PLATE_STEP + 1 ))
printf 'started by : %s\n' "$mode"
printf 'script file : %s\n' "$(basename "${BASH_SOURCE[0]}")"
printf 'own directory : %s\n' "$(basename "$here")"
printf 'bash 4 or newer : %s\n' yes
printf 'config loaded : %s\n' "$(basename "$conf")"
printf 'width range mm : %d to %d step %d\n' "$PLATE_MIN" "$PLATE_MAX" "$PLATE_STEP"
printf 'distinct widths : %d\n' "$steps"
if [ "$mode" = executed ]; then
exit 0
fi
The configuration file beside it, pkg/plates.conf, holds four lines: a comment, then PLATE_MIN=300, PLATE_MAX=1200 and PLATE_STEP=5. A driver starts the tool three ways -- from the parent directory, from inside pkg, and by sourcing it:
#!/usr/bin/env bash
printf '== executed from the parent directory\n'
./pkg/platectl.sh
printf '== executed from inside pkg\n'
( cd pkg && ./platectl.sh )
printf '== sourced into this shell\n'
. ./pkg/platectl.sh
printf 'after sourcing, PLATE_MAX is still set: %s\n' "${PLATE_MAX-unset}"
Output:
== executed from the parent directory
started by : executed
script file : platectl.sh
own directory : pkg
bash 4 or newer : yes
config loaded : plates.conf
width range mm : 300 to 1200 step 5
distinct widths : 181
== executed from inside pkg
started by : executed
script file : platectl.sh
own directory : pkg
bash 4 or newer : yes
config loaded : plates.conf
width range mm : 300 to 1200 step 5
distinct widths : 181
== sourced into this shell
started by : sourced
script file : platectl.sh
own directory : pkg
bash 4 or newer : yes
config loaded : plates.conf
width range mm : 300 to 1200 step 5
distinct widths : 181
after sourcing, PLATE_MAX is still set: 1200
The two executed runs are byte for byte identical even though the current directory differs, which is the entire point of the BASH_SOURCE line. Both find plates.conf because the tool never asks where you are, only where it is. The arithmetic confirms the config was really read rather than defaulted: the range 300 to 1200 in steps of 5 gives 900 divided by 5 plus 1, which is the 181 printed at the bottom.
The sourced run differs in exactly one field and in one invisible way. mode reads sourced because ${BASH_SOURCE[0]} and $0 no longer agree, and the last line proves the consequence: PLATE_MAX is still set in the calling shell afterwards, because nothing was ever a separate process. That is why the failure path uses return 2 when sourced and exit 2 when executed -- calling exit in a sourced file would close the interactive shell of whoever sourced it, which is a memorable way to lose someone's session.
The interpreter guards are cheap and they earn their place. ${BASH_VERSION-} with the dash means "the value, or empty if unset", which is what lets the check work under set -u where a bare $BASH_VERSION would abort the script before it could print its own diagnosis. The BASH_VERSINFO test catches the harder case: a bash that exists but is too old for associative arrays, which describes the bash that still ships as /bin/bash on macOS. Both messages go to standard error and both exit non-zero, so a caller can tell refusal from success without parsing text.
The real design flaw is the line that looks most innocent. . "$conf" does not parse a configuration file; it executes it as bash. Add printf 'the config file just ran a command of its own\n' to plates.conf and that line appears in the output above the report, because the file is code and always was. Anyone who can write plates.conf can therefore run anything as whoever runs platectl.sh, and the tool cannot tell the difference between a config file and a payload. A real version would read the file with a loop that accepts only KEY=VALUE lines for keys it recognises. Two smaller limits are worth stating too: cd resolves symbolic links, so a tool installed as a symlink into /usr/local/bin reports the directory of the real file rather than of the link, which is usually right but is not what the code claims; and the config values are trusted blindly, so a PLATE_STEP of 0 produces a division-by-zero error from the arithmetic rather than a sentence explaining which setting is wrong.
Common Mistakes
- Writing
#!/bin/shat the top of a bash script. On Debian, Ubuntu and most containers/bin/shis dash, not bash. Arrays,[[ ... ]],local,+=on a variable and process substitution all vanish, and the errors point at the line that used the feature rather than at the shebang that removed it. If the script needs bash, name bash.
- Putting options on the shebang line.
#!/usr/bin/env bash -euo pipefaildoes not enable three options; it asks for a program whose name contains spaces and fails with status 127 before your first line runs. Putset -euo pipefailon the second line, where it is portable and visible.
- Saving the file with Windows line endings. A trailing carriage return becomes part of the interpreter name, so the kernel looks for
/usr/bin/env bashfollowed by an invisible byte and reportsbad interpreter: No such file or directoryabout a file you are staring at. Nothing in the message hints at line endings. Set* text=autoand*.sh text eol=lfin.gitattributesand stop guessing.
- Forgetting
chmod +xand misreading the result. Status 126 means "found it, could not execute it", which is a completely different investigation from 127. Learning to read the two numbers apart saves the ten minutes usually spent checking PATH for a permissions problem.
- Expecting your interactive environment inside a script. Aliases, functions,
PATHedits andshoptsettings from~/.bashrcare not there. This is why a command that works perfectly by hand fails under cron with "command not found": cron's PATH is famously short, and your.bashrcnever runs. Set what you need explicitly at the top of the script.
- Using
$0to locate a file meant to be sourced.$0is the caller's name in a sourced file, so a library that computes its own directory from$0will look next to whichever script sourced it.${BASH_SOURCE[0]}is the only correct answer in a file that might be sourced.
- Leaving the directory idiom unquoted.
cd $(dirname $0)breaks the moment the path contains a space, which on macOS and Windows checkouts is routine. The full form, quotes and--included, is longer for a reason:here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd).
- Calling
exitin a file that gets sourced.exitterminates the shell that is running the code, and in a sourced file that shell is the user's own. A library mustreturninstead, which also means it cannot useexitin an error path without first deciding which mode it is in.
- Putting anything before the
#!. A blank line, a licence comment or an editor's byte-order mark all move the shebang off the first two bytes, and the shebang silently becomes a comment. The script then runs under whichever shell happened to invoke it, which is why it passes your test and fails in the pipeline.
Best Practices
- Default to
#!/usr/bin/env bash. It follows PATH, which is what you want when a newer bash is installed alongside an old system one. Use a fixed path only where policy demands it, such as a setuid wrapper or a hardened image where PATH cannot be trusted.
- Put
set -euo pipefailon the line after the shebang. One line, always in the same place, so its absence is visible at a glance. Options belong in the script body, never on the interpreter line.
- Compute the script's own directory once, at the top.
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)and then build every sibling path from$here. Never assume the current working directory; the caller owns that, not you.
- Use functions, not aliases. Alias expansion is off in non-interactive shells and the failure looks like a missing command. Functions work everywhere, take arguments properly and can be exported when they genuinely need to be.
- Declare the environment your script needs instead of inheriting it. Set
PATHexplicitly if you depend on a non-standard location, and read configuration from a file you name rather than from variables you hope are set. Anything that works only because of your shell profile will fail under cron, systemd and CI.
- If a file can be both sourced and executed, say so in the file. Compare
${BASH_SOURCE[0]}with$0once, store the answer, and branch on it wherever you would otherwise callexit. Half-and-half files that were never designed for both modes are a reliable way to kill someone's terminal.
- Keep the executable bit in version control.
git update-index --chmod=+x script.shrecords the mode, so a fresh clone can run the file. A script that needsbash script.shbecause the bit was lost is a script that will eventually be run the wrong way.
- Guard interpreter requirements loudly and early. Check
${BASH_VERSION-}and${BASH_VERSINFO[0]}in the first few lines, write the complaint to standard error and exit with a distinct non-zero status. A clear refusal in line 5 beats an obscure syntax error in line 300.
Practice Exercises
- Collect the three failures. Write one working script, then produce three broken copies: one with the shebang on line 2, one with
#!/usr/bin/env bash -u, and one with the executable bit removed. Run each with./name, record the exact message and the exit status, and write one line explaining which of the two checks at the door failed.
- Prove that your profile does not travel. Add an alias and a
PATHentry to~/.bashrc, then write a script that tries to use both and reports what it found. Run it from your prompt, then again withenv -i /bin/bash script.sh, and finally withBASH_ENVpointing at a file that sets what the script needs. Explain which of the three runs is closest to how cron will start it.
- Make a tool work from anywhere. Create a directory holding a script and a data file. Write the script so it prints the data file's first line correctly whether it is started from inside that directory, from the parent, or by absolute path. Then break it deliberately by using
$PWDinstead, and record what changes.
- Build a dual-mode file. Write a file that defines one function and, when executed directly, runs that function on its arguments; when sourced, it must define the function and nothing else. Prove both behaviours, and prove that the error path does not close your shell when the file is sourced with bad input.