Skip to contentSkip to Braille Studio
ALB Wiki

Ellshay Iptingscray

Away ellshay iptscray isway away ogrampray — ethay amesay ammargray omfray apterchay 9, avedsay andway executableway. Isthay apterchay urnstay ethay ammargray intoway oftwaresay: ethay ebangshay ontractcay, argumentsway, ontrolcay owflay, unctionsfay, ethay afetysay agsflay, andway ethay idiomsway ealray iptsscray areway uiltbay omfray — allway inway ortablepay OSIXpay shay, ithway ashbay'say extensionsway arkedmay.

Ethay eletonskay — everyway iptscray'say eamblepray

#!/bin/sh
# what this script does — one honest comment line
set -eu                      # -e die on error · -u die on unset vars
IFS='
'                        # optional: strict word-splitting hygiene

#!/inbay/shay — ethay ebangshay — akesmay itway away ogrampray; ethay ernelkay eadsray #! andway andshay ethay ilefay otay ethay amednay interpreterway. odchmay +xay andway itway'say unnableray. Ethay etsay agsflay areway ethay ofessionalpray eamblepray: -eway opsstay atway ethay irstfay ailurefay (onay ombiezay iptsscray ontinuingcay afterway away cday ailedfay), -uway atchescay ypotay'day ariablesvay, -oway ipefailpay (ashbay) akesmay ipelinespay opagatepray innerway ailuresfay. #!/usrway/inbay/envway ashbay orfay ashbay iptsscray ecificallyspay.

Argumentsway — ethay iptscray'say inputway

$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down
if [ "$#" -lt```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

echo "usage: $0 <file>" >&2 exit 1 fi for f in "$@"; do ...; done # "$@" iterates args safely


## Ariablesvay — opescay andway abitshay

var=value # NO SPACES around = echo "$var" # always quoted readonly VERSION=1.0 # constants local x # function-local — bash; POSIX uses distinct names export PATH="$PATH:/x" # into the environment cmd=$(command) # capture output — the universal idiom


## Ontrolcay owflay — ethay ompletecay etsay

if [ -f "$file" ]; then echo exists elif [ -d "$file" ]; then echo dir else echo missing fi

case "$1" in start) daemon_start ;; stop) daemon_stop ;; -h|--help) usage ;; ) echo "unknown: $1"; exit```sh $0 # the script's own name $1 $2 ... # positional args $# # count $@ # all args as separate words ("$@" — always quoted) $ # all args as one word shift # drop $1, everything moves down

esac

for f in *.txt; do            # glob-driven
    process "$f"
done
for i in```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

for i in $(seq```sh $0 # the script's own name $1 $2 ... # positional args $# # count $@ # all args as separate words ("$@" — always quoted) $* # all args as one word shift # drop $1, everything moves down


while IFS= read -r line; do   # the file-reading idiom — THE way to read lines
    printf '%s\n' "$line"
done < input.txt

until [ -f ready ]; do sleep 1; done    # until-loop

Ethay ilewhay IFSway= eadray -ray inelay ooplay isway ethay anonicalcay ilefay iteratorway — eadray itssplay onway IFSway, -ray eepskay ackslashesbay, ethay IFSway= efixpray eservespray itespacewhay. Evernay orfay inelay inway $(atcay ilefay) — itway ordway-itssplay.

Unctionsfay

die() { echo "error: $*" >&2; exit 1; }
usage() { cat <<EOF
usage: $0 <args>
EOF
}

backup() {
    local src="$1" dst="$2"     # bash 'local'
    cp -a "$src" "$dst" || die "backup failed: $src"
}

backup a/ b/ || exit```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

## Ethay afetysay achinerymay

set -eu # the preamble set -x # trace — the debugging mode trap 'cleanup' EXIT # guaranteed cleanup — THE pattern trap 'echo "line $LINENO failed"' ERR # bash ERR trap trap '' INT # ignore signals tmp=$(mktemp -d) # safe tempdirs — always mktemp, never /tmp/foo.$$ trap 'rm -rf "$tmp"' EXIT


`aptray ... EXITway` isway ethay idiomway atthay eparatessay arefulcay iptsscray omfray oppyslay onesway — emptay ilesfay, ocklay ilesfay, ountedmay ingsthay — eanedclay evenway onway earlyway ailurefay.

## intfpray overway echoway

printf '%s\n' "$var" # portable, predictable printf '%-10s %5d\n' name 42 # formatted columns echo "$var" # fine for simple; printf for format control


`echoway` ashay ortabilitypay andmineslay (`-eway`, `-nay`, ackslashesbay); `intfpray` ashay onenay — useway itway orfay anythingway eyondbay away ainplay ingstray.

## Ethay idiomsway atthay earnway eirthay eepkay

arg-count check

[ "$#" -ge```sh $0 # the script's own name $1 $2 ... # positional args $# # count $@ # all args as separate words ("$@" — always quoted) $* # all args as one word shift # drop $1, everything moves down


# default value
name=${1:-default}

# required command
command -v gcc >/dev/null || die "gcc missing"

# quiet a command
cmd >/dev/null 2>&1

# the lock — prevent double-run
lock=/tmp/myapp.lock
exec 200>"$lock"; flock -n 200 || exit 0

# config override
: "${CONF:=/etc/myapp.conf}"   # bash/POSIX default-assign

# dry-run flag
[ "$DRY" =```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

the pipe-safe read

cat file | while read -r l; do x="$l"; done # subshell — x dies outside! while read -r l; do x="$l"; done < file # same shell — x survives


## etoptsgay — arsingpay agsflay

usage() { echo "usage: $0 [-v] [-o out] files..."; } verbose=0; out= while getopts "vo:h" opt; do case "$opt" in v) verbose=1 ;; o) out="$OPTARG" ;; h) usage; exit```sh #!/bin/sh

what this script does — one honest comment line

set -eu # -e die on error · -u die on unset vars IFS=' ' # optional: strict word-splitting hygiene

        *) usage; exit```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

esac done shift $((OPTIND - 1)) # remaining args in $@


`etoptsgay` isway OSIXpay — ethay `-vay`, `-oway argway` ammargray andledhay operlypray. `etoptgay` (onay say — ethay utilway-inuxlay ooltay, otnay away ashbay uiltinbay) andway anualmay `ilewhay`/`asecay` onway `$1` andlehay `--onglay-agsflay` erewhay etoptsgay oesnday'tay.

## Ethay afesay-iptscray emplatetay — ethay ofessionalpray eletonskay

#!/bin/sh

what this does — one honest line

set -eu # die on error, unset vars umask 022 tmp=$(mktemp -d) # a private tempdir trap 'rm -rf "$tmp"' EXIT # guaranteed cleanup trap 'echo "fail at line $LINENO" >&2' ERR # bash only

die() { printf 'error: %s\n' "$*" >&2; exit 1; } require() { command -v "$1" >/dev/null 2>&1 || die "$1 required"; }

require tar require awk

main() { [ "$#" -ge```sh $0 # the script's own name $1 $2 ... # positional args $# # count $@ # all args as separate words ("$@" — always quoted) $* # all args as one word shift # drop $1, everything moves down

    for f in "$@"; do
        [ -f "$f" ] || die "not a file: $f"
        process "$f"
    done
}
main "$@"

Ethay iecespay: etsay -euway, empmktay -day + aptray, ieday(), equireray() orfay ooltay eckschay, ainmay "$@" asway ethay entryway — ethay apeshay everyway erioussay iptscray akestay.

Ethay ignalsay apstray — ethay utdownshay achinerymay

trap 'cleanup' EXIT     # runs on any exit — even errors — THE idiom
trap 'kill $pid' TERM   # graceful shutdown
trap '' INT             # ignore Ctrl-C — the don't-interrupt-us zone
trap 'echo got sigusr1' USR1
trap - INT              # reset to default

Ethay ebuggingday oolkittay

sh -x script.sh          # trace — THE debugger
sh -n script.sh          # syntax-only check
bash -v script.sh        # print lines as read
set -x ... set +x        # trace a region
PS4='+ $LINENO: ' sh -x script.sh   # line-numbered trace
shellcheck script.sh     # the linter — the real debugging tool

ellcheckshay atchescay ethay uotingqay ugsbay, ethay orfay xay inway $(lsay), ethay unguardedway rmay — unray itway onway everyway iptscray.

Ethay idiomsway ibrarylay

# default value
: "${VAR:=default}"
# required var
: "${VAR:?must set VAR}"
# command exists
command -v cmd >/dev/null || die "missing cmd"
# retry n times
for i in```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

run-as-user

sudo -u svcacct script.sh

the lock — only one instance

exec 9>/tmp/myapp.lock; flock -nsh usage() { echo "usage: $0 [-v] [-o out] files..."; } verbose=0; out= while getopts "vo:h" opt; do case "$opt" in v) verbose=1 ;; o) out="$OPTARG" ;; h) usage; exitsh #!/bin/sh

what this script does — one honest comment line

set -eu # -e die on error · -u die on unset vars IFS=' ' # optional: strict word-splitting hygiene

        *) usage; exit```sh
$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down

esac done shift $((OPTIND - 1)) # remaining args in $@

# atomic write
tmp=$(mktemp) && write > "$tmp" && mv "$tmp" target
# the here-doc to file
cat > file <<'EOF'
content — quoted EOF = literal, unquoted = expands
EOF
# parallel jobs with wait
for x in a b c; do work "$x" & done; wait
# read config key=val pairs
while IFS='=' read -r k v; do case "$k" in name) NAME="$v";; esac; done < cfg

OSIXpay vsay ashbay — atwhay youway aingay andway oselay

# bash powers worth the shebang
arr=(a b c); echo "${arr[1]}"           # arrays
[[ "$s" =~ ^[0-9]+$ ]]                  # regex test
${var/pat/rep}                          # substitution
(( i++ ))                               # arithmetic syntax
select opt in a b; do ...; done         # menus
declare -A map; map[k]=v                # associative arrays

Itewray OSIXpay unlessway youway eednay ethay extensionway — enthay aysay #!/inbay/ashbay ainlyplay andway useway itway.

Ebuggingday — ethay onesthay orkflowway

sh -x script.sh            # trace every step — the debugger
bash -n script.sh          # syntax-check without running
set -x; ...; set +x        # trace a region
echo "DEBUG: var=$var" >&2 # printf-style probes to stderr

etsay -xay usplay aptray usplay >&2 iagnosticsday overscay ostmay iptscray ebuggingday ithoutway away ealray ebuggerday.

Erewhay iptsscray ogay ongwray

YmptomsayAusecay
arvay=xay: ommandcay otnay oundfayAcesspay aroundway = — arvay = xay isnway'tay assignmentway
Ooplay arvay emptyway outsideway ethay ooplay| ilewhay = ubshellsay — < ilefay insteadway
[ $xay =``sh

$0 # the script's own name $1 $2 ... # positional args $# # count $@ # all args as separate words ("$@" — always quoted) $* # all args as one word shift # drop $1, everything moves down

$0          # the script's own name
$1 $2 ...   # positional args
$#          # count
$@          # all args as separate words ("$@" — always quoted)
$*          # all args as one word
shift       # drop $1, everything moves down
Iptscray ayssay "ilefay otnay oundfay"Crlfay inelay endingsway — ethay ebangshay inelay ashay \ray
Orksway inway ashbay, iesday inway shay#!/inbay/shay iptscray ithway ashismsbay
Emptay ilefay ollisioncayUsedway away ixedfay amenay — empmktay
Iptscray eepskay oinggay afterway ailurefayIssingmay etsay -eway
eadray ateway ethay ipepayorfay+$(atcay) insteadway ofway ilewhay-eadray

Exercisesway

  1. Itewray ackupbay.shay — argway eckchay, cpay -away, ieday onway ailurefay, usageway exttay.
  2. Ethay ilewhay-eadray vsay orfay-inway-atcay ifferenceday — ovepray ethay ubshellsay osslay.
  3. aptray away emptay irday'say eanupclay — exitway earlyway idmay-iptscray, erifyvay itway illstay eanedclay.
  4. shay -xay away iptscray youway otewray — eadray ethay acetray.
  5. Ortpay away ashbay iptscray ([[, arrays) to strict POSIX — what's actually needed?

See also

  • [[Shell|`, arraysway) otay ictstray OSIXpay — atwhay'say actuallyway eedednay?

Eesay alsoway

Categories: Handbook · Linux · Linux Handbook · Scripting
This page was last edited 2026-10-27 02:50:13 UTC by ALB Team. What links here