Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Shell Scripts

Direct answer

A shell script is a text file of shell commands with a shebang line (#!/bin/bash) and execute permission, used to automate tasks.

When to use this

Use it to automate repeated tasks, or when a script fails, behaves differently from manual commands, or will not run.

First 30 seconds

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.

Operational verification

file with shebang and +x → kernel starts the interpreter → commands run in order → exit code returned

Evidence · next step

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
Platform / version applicability
linux
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformlinux
Scope / prerequisiteUse it to automate repeated tasks, or when a script fails, behaves differently from manual commands, or will not run.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

5 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points

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.

Key checks
  • file script.sh — detects CRLF line endings
  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — 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 pipefail is set.
  • Builtins return 2 for incorrect usage.

A template

ElementPurpose
#!/usr/bin/env bash or #!/bin/bashThe interpreter (use #!/bin/sh only for POSIX-only scripts)
set -euo pipefailStop on errors, unset variables and failed pipeline parts
IFS=$'\n\t' (optional)Safer word splitting
trap cleanup EXITRemove temporary files whatever happens
usage() and argument checksA clear message instead of strange failures
Quoted variables everywhereNo 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor doclinux current

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%
Technical changelog & impact

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.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

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.

Aliases that resolve here
bash scriptsshell scripting linuxlinux shell scriptbash script troubleshooting
Embedded reference data

Quick lookup tables

Shell Scripts operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Shell Scripts.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateShell 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 verificationPin 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 chaincaller/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 testTrace requested/configured state through effective state to the observed workload result.
Failure boundaryScript 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 evidenceCorrelated 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 testUse this observation only for the specific claim it actually supports.
Evidence limitIt 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 checkContinue 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 boundaryShell Scripts
Topic pathShell & Bash → Shell Scripts
Runtime stateShell 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 chaincaller/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 boundaryScript 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 ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?