Use it to automate repeated tasks, or when a script fails, behaves differently from manual commands, or will not run.
Shell Scripts
A shell script is a text file of shell commands with a shebang line (#!/bin/bash) and execute permission, used to automate tasks.
1. "Permission denied" → chmod +x script.sh; noexec mount?
2. "bad interpreter" → wrong shebang or CRLF: file script.sh.
3. shellcheck script.sh — fix warnings.
4. bash -x script.sh — trace.
5. Check $? and logs.
file with shebang and +x → kernel starts the interpreter → commands run in order → exit code returned
For Shell & Bash → Shell Scripts, continue with the first unproven Topic check: Record exact invocation, interpreter/version, cwd, uid/gid, environment/PATH, shell options and inputs. If that boundary is healthy, advance to the adjacent check: Validate parameters and quote/array data so filenames/values do not become code, options or unintended words. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.
Continue only after interpreting the current observation.Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Operational evidence path Verify boundary
caller/invocation → interpreter/shebang → cwd + identity + environment/PATH → parse/expand → commands/pipelines/redirections → side effects + per-step status → cleanup/traps → script exit → target read-back + acceptance test
Healthy evidence: exact interpreter/context is known, inputs/quoting/error handling are deterministic, partial failures are surfaced and target plus workload verification passes.
Step 2 Verification and output interpretation Verify boundary
Existing fast checks for this Topic. - Record exact invocation, interpreter/version, cwd, uid/gid, environment/PATH, shell options and inputs.
- Validate parameters and quote/array data so filenames/values do not become code, options or unintended words.
- Define explicit error/status handling for pipelines, cleanup/traps and partial changes.
- Read back each critical target state and run an end-to-end acceptance test rather than trusting script exit status.
Verification chain. caller/invocation → interpreter/shebang → cwd + identity + environment/PATH → parse/expand → commands/pipelines/redirections → side effects + per-step status → cleanup/traps → script exit → target read-back + acceptance test
Step 3 Commands Verify boundary
#!/usr/bin/env bash
set -euo pipefail
shellcheck script.sh
Step 4 Failure modes and next checks Narrow the fault
Suspicious evidence: a different interpreter/PATH/cwd changes behavior, set -e assumptions hide errors, or exit 0 is accepted despite partial/ineffective side effects.
Step 5 Common mistakes Narrow the fault
- Scripts without a shebang or execute bit.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
Make it executable (chmod +x), start with set -euo pipefail, quote variables, use full paths in cron, and check with shellcheck. Windows line endings (\r) cause "bad interpreter" errors — fix with dos2unix.
file script.sh— detects CRLF line endingsbash -x script.sh— trace each expanded commandbash -n script.sh— syntax check onlyshellcheck script.sh— common bugs and quoting problemsecho $?— exit code of the last command
ReferenceWhat it is1 section · depth on demand
Core model
Start from the invocation path: executable file with shebang, explicit interpreter, sourced file or command string. Resolve interpreter and cwd, validate inputs, quote data, preserve pipeline failures, use predictable temporary/error handling and verify target state after commands that change it.
ReferenceImportant terms & boundaries5 sections · depth on demand
What this shows and what it does not
Script success is an orchestration signal, not evidence of desired target state; verification must cover effective state and the workload the script intended to enable.
In depth
Writing robust shell scripts
A shell script is a file of commands run by a non-interactive shell. The bash(1) manual page notes several things that matter for scripts:
- Non-interactive shells read no startup files except one named in
BASH_ENV, so scripts must set their own environment. - Aliases aren't expanded.
- A pipeline's status comes from the last command, unless
pipefailis set. - Builtins return 2 for incorrect usage.
A template
| Element | Purpose |
|---|---|
#!/usr/bin/env bash or #!/bin/bash | The interpreter (use #!/bin/sh only for POSIX-only scripts) |
set -euo pipefail | Stop on errors, unset variables and failed pipeline parts |
IFS=$'\n\t' (optional) | Safer word splitting |
trap cleanup EXIT | Remove temporary files whatever happens |
usage() and argument checks | A clear message instead of strange failures |
| Quoted variables everywhere | No accidental splitting or globbing |
Limits of set -e
set -e doesn't stop the script for commands in if and while conditions, in && and || lists, or for most failures inside command substitutions used as arguments. Explicit checks are still needed where failure matters.
host$ cat /usr/local/bin/rotate-exports
#!/usr/bin/env bash
set -euo pipefail
usage() { echo "usage: ${0##*/} <dir> <days>" >&2; exit 2; }
[[ $# -eq 2 ]] || usage
dir=$1 days=$2
[[ -d $dir ]] || { echo "no such directory: $dir" >&2; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
find "$dir" -name '*.csv' -mtime +"$days" -print0 > "$tmp/list"
count=$(tr -cd '\0' < "$tmp/list" | wc -c)
xargs -0 -r gzip -9 < "$tmp/list"
echo "compressed $count file(s) in $dir"
host$ chmod 755 /usr/local/bin/rotate-exports
host$ shellcheck /usr/local/bin/rotate-exports
host$ bash -n /usr/local/bin/rotate-exports && rotate-exports /srv/export 30
compressed 12 file(s) in /srv/export
host$ bash -x /usr/local/bin/rotate-exports /srv/export 30 2>&1 | head -5
Notes on the template
-print0 with xargs -0 handles file names with spaces and newlines safely. mktemp -d together with the EXIT trap guarantees cleanup, even when set -e stops the script half-way. shellcheck catches most quoting and portability mistakes before the script runs.
Documented example, not captured output.
How it works at runtime
Shell Scripts is part of Shell & Bash → Shell Scripts. Shell Scripts package shell syntax into repeatable executable or sourced files; interpreter selection, permissions, working directory, environment, strictness options and caller context determine their real behavior.
Topic-specific state model. Shell Scripts package shell syntax into repeatable executable or sourced files; interpreter selection, permissions, working directory, environment, strictness options and caller context determine their real behavior.
Interpretation rule. - Executable bit + shebang ≠ interpreter used when the file is invoked as bash script or sh script.
- set -e ≠ complete error handling and set -u/pipefail ≠ correctness.
- Script exits 0 ≠ every external side effect reached desired/effective state.
- Working in an interactive shell ≠ script has same cwd, PATH, environment, TTY or startup files.
Quick reference
A robust Bash script skeleton:
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
trap 'echo "error on line $LINENO" >&2' ERR
trap 'rm -rf "$tmp"' EXIT
tmp=$(mktemp -d)
usage() { echo "usage: $0 -h host [-n]" >&2; exit 2; }
dry=0
while getopts 'h:n' o; do case $o in h) host=$OPTARG;; n) dry=1;; *) usage;; esac; done
: "${host:?$(usage)}"
log() { printf '%s %s\n' "$(date +%FT%T)" "$*" >&2; }
log "checking $host"
(( dry )) || ssh "$host" 'systemctl is-active nginx'
Run shellcheck script.sh before deploying; it catches quoting and portability bugs.
Limits and how it fails
Primary failure point. Script success is an orchestration signal, not evidence of desired target state; verification must cover effective state and the workload the script intended to enable.
ReferenceConfiguration & state1 section · depth on demand
Configuration, persistence and lifecycle
Distribution/platform context. Scripting in Automation owns language-agnostic scripting practice; this Topic owns Linux shell-script execution semantics and Bash/sh pitfalls.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Shell & Bash → Shell Scripts. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%What changed and what may be affected
Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.
Terms & aliases
Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.
Quick lookup tables
Shell Scripts operational reference
Topic-specific lookup boundaries, proof limits and next-step Evidence for Shell Scripts.
| Lookup boundary | Topic-specific reference | Operational use |
|---|---|---|
| Scope / effective state | Shell Scripts package shell syntax into repeatable executable or sourced files; interpreter selection, permissions, working directory, environment, strictness options and caller context determine their real behavior. | Establish exactly what this Topic owns before crossing into another subsystem. |
| Fast verification | Pin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test. | Use the shortest evidence path first; a fast check is a boundary test, not blanket proof. |
| Verification chain | caller/invocation → interpreter/shebang → cwd + identity + environment/PATH → parse/expand → commands/pipelines/redirections → side effects + per-step status → cleanup/traps → script exit → target read-back + acceptance test | Trace requested/configured state through effective state to the observed workload result. |
| Failure boundary | Script success is an orchestration signal, not proof of desired target state; verification must cover effective state and the workload the script intended to enable. | Stop broad troubleshooting at the first boundary that is not supported by evidence. |
| Positive evidence | Correlated Linux file/text/shell evidence can establish this proof path: caller/invocation → interpreter/shebang → cwd + identity + environment/PATH → parse/expand → commands/pipelines/redirections → side effects + per-step status → cleanup/traps → script exit → target read-back + acceptance test | Use this observation only for the specific claim it actually supports. |
| Evidence limit | It does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Script success is an orchestration signal, not proof of desired target state; verification must cover effective state and the workload the script intended to enable. | Do not promote a local success signal into end-to-end or adjacent-dependency proof. |
| Next troubleshooting check | Continue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks. | Continue to the next unresolved boundary while preserving the original test condition. |
Shell Scripts · operational reference
Compact Linux state, persistence, verification and boundary reference for fast lookup.
| Reference boundary | Shell Scripts |
|---|---|
| Topic path | Shell & Bash → Shell Scripts |
| Runtime state | Shell Scripts package shell syntax into repeatable executable or sourced files; interpreter selection, permissions, working directory, environment, strictness options and caller context determine their real behavior. |
| Fast checks | - Record exact invocation, interpreter/version, cwd, uid/gid, environment/PATH, shell options and inputs. - Validate parameters and quote/array data so filenames/values do not become code, options or unintended words. - Define explicit error/status handling for pipelines, cleanup/traps and partial changes. - Read back each critical target state and run an end-to-end acceptance test rather than trusting script exit status. |
| Verification chain | caller/invocation → interpreter/shebang → cwd + identity + environment/PATH → parse/expand → commands/pipelines/redirections → side effects + per-step status → cleanup/traps → script exit → target read-back + acceptance test Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary. |
| Failure boundary | Script success is an orchestration signal, not proof of desired target state; verification must cover effective state and the workload the script intended to enable. Boundary chain: process/socket namespace → source/rule/FIB → neighbor → netfilter/eBPF/qdisc → virtual/physical device → peer → return → application. |
| Persistence rule | Prove which configuration source owns the state, then prove that the running consumer loaded or generated the intended state. |