The Analogy: The Press Photographer's Lens Kit
A working press photographer carries one camera body and a bag of interchangeable lenses. The body -- the shutter, the sensor, the basic controls -- is the same for every shot. What changes is the glass mounted on the front: a fast prime for a dim room, a long telephoto for the touchline, a wide angle for the crowd, a macro for the medal close-up. Each lens is a specialized instrument that does one job the general-purpose kit lens does clumsily or not at all.
The skill is not owning the lenses; it is knowing which one the moment demands and mounting it before the moment passes. The telephoto pulls a distant face across the stadium, but its narrow field means a step too far and the subject is gone. The wide angle sweeps in the whole scene, but pushed too close it makes faces bulge and bend. The macro renders a coin's every scratch, but its paper-thin depth of field means a millimeter of focus error and the whole frame is soft. The lens multiplies what a skilled hand can do and, in the same motion, multiplies the cost of a careless one.
A photographer who has internalized the kit works without thinking about it: sees the shot, reaches for the right glass, sets aperture and focus for what that lens does well. The specialized tool, used within its envelope, produces a picture the basic lens simply cannot -- the isolated face against a melted background, the insect's eye filling the frame. Reach and result feel effortless because the tool fits the task.
But every specialized lens has an envelope, and outside it the very quality that made it powerful turns against you. The telephoto that isolates a face also magnifies the smallest shake into a blurred ruin. The macro's exquisite shallow focus, aimed a hair off, puts the eyes out and the ear in. Mount the wrong lens for the moment, or the right lens set wrong, and you do not get a merely ordinary photograph -- you get a worse one than the plain kit lens would have given, taken with more confidence. Power you do not match to the task is not neutral; it costs you the shot.
Syntax or Core Structure
Beyond the everyday commands lies a set of built-in constructs Bash provides for jobs the basics do awkwardly: integer arithmetic, regular-expression matching, sequence generation, and formatting into a variable. The most fundamental is arithmetic evaluation. Inside double parentheses, (( ... )), Bash treats its contents as an integer expression -- names need no $, and C-style operators like ++, *, and <= all work.
count=0
(( count = 3 * 4 ))
echo "count is $count"
for (( i = 1; i <= 3; i++ )); do
echo "row $i"
done
Output:
count is 12
row 1
row 2
row 3
The arithmetic-for loop, for (( i = 1; i <= 3; i++ )), is the natural companion -- a counted loop that reads like C rather than the word-list for you use elsewhere. But (( )) carries a sharp edge: its exit status is 0 only when the expression is non-zero, so (( count = 0 )) reports "failure", and under set -e that can abort a script which did nothing wrong.
Technical Depth: Four Instruments and Their Envelopes
Four built-in constructs cover most of what pushes a script past the basics. Each is a specialized lens: powerful within its envelope, and quietly damaging outside it.
| Feature | Construct | Use it for |
|---|---|---|
| Arithmetic | (( ... )) | integer math and numeric conditions |
| Regex match | [[ str =~ re ]] | validating and parsing text |
| Brace expansion | {a,b} and {1..9} | generating sequences and filename sets |
| printf into a var | printf -v name | formatting a string without a subshell |
More arithmetic: operators, ternary, and bases
Arithmetic context is a small C dialect. Alongside the everyday operators it offers exponentiation **, modulo %, the ternary cond ? a : b, and base prefixes such as 16#ff for hexadecimal or 2#1010 for binary. Because the value is what you want here, each line wraps the expression in $(( )).
echo "$(( 2 ** 10 ))"
echo "$(( 17 % 5 ))"
echo "$(( 8 > 3 ? 8 : 3 ))"
echo "$(( 16#ff ))"
Output:
1024
2
8
255
The compound assignment operators work too, mutating a variable in place. Here the bare (( )) form is right, because we care about the side effect on total, not a substituted value.
total=10
(( total += 5 ))
(( total *= 2 ))
echo "$total"
Output:
30
Matching and parsing text with =~
The =~ operator inside [[ ]] matches a string against a POSIX extended regular expression. The pattern must be left unquoted -- quoting it turns the regex into a literal string. On a match, the whole matched text and any parenthesized capture groups land in the BASH_REMATCH array.
ip="10.0.0.5"
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "looks like an IPv4 address"
fi
d="2020-07-15"
if [[ $d =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
echo "year=${BASH_REMATCH[1]} month=${BASH_REMATCH[2]}"
fi
Output:
looks like an IPv4 address
year=2020 month=07
BASH_REMATCH[0] holds the entire match and [1], [2], and so on hold the capture groups left to right. The array is global and is overwritten by the next successful match, so copy out anything you need before matching again.
Two habits keep this honest. Anchor with ^ and $ whenever you mean the whole string, or a bare pattern will match any input that merely contains it and wave through data you meant to reject. And prefer POSIX classes such as [[:digit:]] and [[:space:]] over raw ranges when portability matters: [0-9] can depend on the locale's collation order, while the named classes always mean what they say.
Generating sequences with brace expansion
Brace expansion turns a compact pattern into a list of words before any command runs. A comma list expands to each alternative; a numeric or alphabetic range with .. expands to the whole run, and a leading zero pads the width.
echo file-{01..03}.log
echo {dev,staging,prod}-config
Output:
file-01.log file-02.log file-03.log
dev-config staging-config prod-config
Adjacent brace expressions multiply: every element of the first pairs with every element of the second, a compact way to build a matrix of names.
echo {a,b}{1,2}
Output:
a1 a2 b1 b2
The envelope is timing. Brace expansion happens before variable expansion, so a variable inside the range is not yet a number when the braces are evaluated. The braces are left untouched, and only afterwards does the variable expand -- giving a literal string, not a sequence.
n=3
echo {1..$n}
Output:
{1..3}
Formatting into a variable with printf -v
Normally you capture formatted text with x=$(printf ...), which forks a subshell. The -v flag tells printf to assign its result directly into a named variable in the current shell instead, avoiding the fork entirely.
printf -v padded '%04d' 42
echo "$padded"
Output:
0042
A format string can carry width and justification flags, so printf -v is the clean way to build an aligned table row inside a variable -- left-justify a label, right-justify a number -- with no subshell involved.
printf -v row '%-8s %5d' widget 42
echo "[$row]"
Output:
[widget 42]
That distinction matters most in a loop. Writing x=$(printf ...) forks a subshell on every iteration, while printf -v x ... stays in the current shell and touches no new process. Over thousands of rows that is the difference between a script that feels instant and one that visibly grinds.
Real World Example: A Log-Level Scanner
This scanner reads log lines on standard input, validates each against a fixed shape with [[ =~ ]], pulls the level out of the capture group, and tallies the counts with (( )). Anything that does not match the expected shape is counted as bad. It combines three of the four instruments in one small, self-contained program.
#!/usr/bin/env bash
# scan-log.sh -- classify log lines by level using [[ =~ ]] and (( ))
set -uo pipefail
errors=0
warns=0
infos=0
bad=0
while IFS= read -r line; do
if [[ $line =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}\ (ERROR|WARN|INFO)\ (.+)$ ]]; then
level="${BASH_REMATCH[1]}"
case "$level" in
ERROR) (( errors++ )) ;;
WARN) (( warns++ )) ;;
INFO) (( infos++ )) ;;
esac
else
(( bad++ ))
fi
done
total=$(( errors + warns + infos ))
printf 'errors=%d warns=%d infos=%d valid=%d bad=%d\n' "$errors" "$warns" "$infos" "$total" "$bad"
The regex anchors the whole line: four-two-two digits, a literal space (written \ so the space is part of the pattern rather than a token separator), one of three levels, another space, and a non-empty message. The first capture group is the level, which drives a case that bumps the matching counter. Feed it five lines -- four well-formed at three levels, one line of garbage -- on standard input.
2020-01-01 ERROR disk full
2020-01-01 WARN low memory
2020-01-01 INFO started
2020-01-01 ERROR timeout
garbage line
Running bash scan-log.sh against that input produces a single deterministic summary line: two errors, one warning, one info, four valid lines, one bad.
Output:
errors=2 warns=1 infos=1 valid=4 bad=1
The script leans on its instruments well, but two flaws hide in plain sight. First, it runs set -uo pipefail but deliberately not -e -- and it has to, because (( errors++ )) returns exit status 1 the first time it runs while the counter is still zero, so set -e would abort the scan on the very first error line. That is the arithmetic-status trap wearing a disguise, and the script is one well-meant flag away from breaking. Second, bad conflates two unrelated failures: a truly malformed line and a perfectly well-formed line whose level is simply not one of the three the regex knows. A line like 2020-01-01 DEBUG trace on is counted as bad even though it is valid, because the alternation lists only ERROR, WARN, and INFO. The message capture group is extracted and then ignored, and the date is checked for shape but not validity, so 9999-99-99 would sail through. Each is the kind of gap a green run never reveals.
Common Mistakes
- Quoting the regex in
[[ =~ ]]. Writing[[ $s =~ "^[0-9]+$" ]]makes Bash match the pattern as a literal string, not a regex, so it almost never matches. Leave the regex unquoted, or store it in a variable and use the variable unquoted.
- Assuming
(( ))always succeeds. Its exit status is 1 whenever the expression evaluates to zero, so(( x = 0 ))and(( count++ ))from zero both report failure. Underset -ethat aborts the script; guard with|| trueor use a plain assignment when you only want the arithmetic.
- Expecting brace expansion to see variables.
{1..$n}does not expand into a sequence, because brace expansion runs before$nis substituted. Use a C-style loop orseqwhen the bound is a variable.
- Confusing
(( ))with$(( )).(( expr ))evaluates the expression and sets an exit status;$(( expr ))evaluates it and substitutes the result as text. Use the first for conditions and side effects, the second where you need the value.
- Using
=~for a fixed substring. A regular expression for a literal substring is overkill and breaks the moment the string contains a metacharacter. Use glob matching,[[ $s == *needle* ]], for plain substrings.
- Forgetting
BASH_REMATCHis clobbered. Every successful=~overwrites the whole array. Copy the captures you need into named variables before the next[[ =~ ]]runs, or you will read the wrong match.
- Relying on
printf -vinside a subshell.printf -vassigns in the current shell; run it inside$( )or a pipeline and the assignment vanishes when the subshell exits. Keep it in the same shell as the variable you mean to set.
- Writing
$on the counter inside(( )). In arithmetic context you writeiandi++, not$i; a stray$substitutes the value first and usually breaks the expression. Drop the$inside(( )).
- Treating advanced features as always clearer. A regex where a
caseglob would read better, or(( ))where a simple comparison suffices, trades legibility for cleverness. Reach for the power feature only when the basic construct genuinely falls short.
Best Practices
- Reach for a power feature only when the basic tool falls short.
(( )),[[ =~ ]], and brace expansion earn their place on real numeric, parsing, and sequence work; on trivial cases a plain comparison orcasereads better and surprises no one.
- Do integer math in
(( ))and take values with$(( )). Keep names bare inside arithmetic, and reserve$(( ))for when you need the computed result as text.
- Guard
(( ))against its zero-result status. When a zero result is legitimate, append|| trueor use: $(( ... ))soset -edoes not mistake successful arithmetic for a failed command.
- Leave regexes unquoted and store complex ones in a variable.
re='^[0-9]+$'; [[ $s =~ $re ]]is readable and sidesteps the quoting trap; quoting the pattern silently disables regex matching.
- Copy
BASH_REMATCHimmediately. Assign the capture groups you need to named variables right after the match, before any later=~overwrites the array.
- Prefer
printf -vover command substitution for formatting. It sets the variable in place without forking a subshell, which is faster and keeps the assignment in the current shell where you can use it.
- Use brace expansion for literal sequences and loops for variable bounds.
{01..12}is perfect for a fixed range; when a bound comes from a variable, switch to a C-stylefor (( ))loop.
- Comment the intent of a dense construct. A one-line note above a gnarly regex or arithmetic expression saves the next reader from reverse-engineering the shape you expected.
Practice Exercises
- Validate with a stored regex. Write a function that accepts a string and returns success only if it matches a
YYYY-MM-DDshape. Store the pattern in a variable, match it unquoted with[[ =~ ]], and prove it accepts2020-01-01and rejects2020-1-1.
- Tally with arithmetic, safely. Count how many numbers in a list are even using
(( )), and make the loop surviveset -eeven when the running count passes through zero. Explain where the|| trueor: $(( ))guard goes and why it is needed.
- Generate a filename set. Use brace expansion to print
report-01.csvthroughreport-12.csvon one line, then show why{1..$month}fails when$monthis a variable and rewrite it with a loop.
- Format without a subshell. Use
printf -vto build a zero-padded, fixed-width table row from three fields, then compare it with the$(printf ...)version and note which one avoids forking a subshell.