Arrays, Associative Arrays, and Arithmetic
Store lists and key-value maps safely in Bash arrays, build command lines without quoting bugs, count things with associative arrays, and do integer and decimal math correctly.
By The Dark DebuggerUpdated 30 min read
This article covers Bash's two data structures, indexed arrays and associative arrays, and its integer arithmetic, including how to get decimals when integers aren't enough. It builds on Loops, Functions, and Reading Input, so you should be comfortable with for loops, while read and functions. The next article, Error Handling, Traps, and Debugging, relies on several things introduced here, such as PIPESTATUS and arithmetic conditions.
Why arrays
A plain variable holds one string. The moment you need a list (filenames, servers, command-line options), a string forces you to pick a separator, and the data eventually contains it: a filename with a space, a path with a comma. Arrays hold each item separately, so nothing is ever re-split.
Associative arrays add the other structure you keep reaching for: a lookup table. Requests per HTTP status code, a threshold per mount point, settings by name. With these two and integer arithmetic, a lot of jobs that seem to need Python can stay as a short, dependency-free script, and we'll finish with one: a disk-usage checker with per-filesystem thresholds.
Indexed arrays: creating and reading
Create an array with parentheses. Elements are numbered from 0:
servers=(web01 web02 db01)
echo "${servers[0]}"
echo "${servers[2]}"
echo "${servers[-1]}"
echo "${#servers[@]}"
echo "${servers[@]}"web01
db01
db01
3
web01 web02 db01The braces are required: $servers[0] would expand $servers and then print a literal [0]. Negative indices count from the end, ${#servers[@]} is the number of elements, and ${servers[@]} is all of them.
One surprise: the array name on its own means element 0, not the whole array:
echo "$servers"
declare -p serversweb01
declare -a servers=([0]="web01" [1]="web02" [2]="db01")declare -p prints any variable exactly as Bash stores it. It's the best debugging tool for arrays, because it shows the indices and the quoting.
Adding, replacing and removing elements
+=( … ) appends. Assigning to an index sets that element, and indices don't have to be contiguous:
servers+=(cache01)
servers[10]=backup01
declare -p servers
echo "${#servers[@]} elements, indices: ${!servers[@]}"declare -a servers=([0]="web01" [1]="web02" [2]="db01" [3]="cache01" [10]="backup01")
5 elements, indices: 0 1 2 3 10Bash arrays are sparse: there is no element 4 through 9, and the length is 5, not 11. ${!servers[@]} lists the indices that exist. unset removes an element and leaves a gap; re-assigning the array from itself closes the gaps:
unset 'servers[1]'
declare -p servers
servers=("${servers[@]}")
declare -p serversdeclare -a servers=([0]="web01" [2]="db01" [3]="cache01" [10]="backup01")
declare -a servers=([0]="web01" [1]="db01" [2]="cache01" [3]="backup01")Quote the argument to unset. Unquoted, servers[1] is a glob pattern (matching a file named servers1), and if such a file exists in the current directory, Bash unsets the wrong thing.
Expanding arrays correctly: "${a[@]}"
This is the part that matters most. Here is an array of filenames, two with spaces, expanded three ways:
files=("access log.txt" "error.log" "app 2026-11-01.log")
printf '[%s]\n' "${files[@]}"
printf '[%s]\n' ${files[@]}
printf '[%s]\n' "${files[*]}"[access log.txt]
[error.log]
[app 2026-11-01.log]
[access]
[log.txt]
[error.log]
[app]
[2026-11-01.log]
[access log.txt error.log app 2026-11-01.log]It is the same rule as "$@" versus "$*" from Your First Scripts:
"${files[@]}"gives one word per element, untouched. Use this almost always.${files[@]}without quotes re-splits on spaces and expands globs. The array was pointless."${files[*]}"joins all elements into one string, separated by the first character ofIFS.
So the loop is always written with quotes and [@]:
for f in "${files[@]}"; do echo "file: $f"; done
for i in "${!files[@]}"; do echo "$i: ${files[i]}"; donefile: access log.txt
file: error.log
file: app 2026-11-01.log
0: access log.txt
1: error.log
2: app 2026-11-01.logLoop over "${!files[@]}" when you need the index too. Inside [ ] the index is evaluated as arithmetic, so files[i] works without a $.
"${files[*]}" is useful on purpose when you want to join. Change IFS inside a subshell (the parentheses) so the change doesn't leak into the rest of the script:
(IFS=,; echo "${files[*]}")access log.txt,error.log,app 2026-11-01.logSlicing and transforming
${a[@]:start:count} takes a slice, and the parameter-expansion operators you know from strings apply to every element at once:
nums=(10 20 30 40 50)
echo "${nums[@]:1:2}"
echo "${nums[@]:2}"
echo "${nums[@]: -2}"
logs=(api.log worker.log "batch run.log")
printf '%s\n' "${logs[@]%.log}"
printf '%s\n' "${logs[@]/#/--exclude=}"
echo "${#logs[2]}"20 30
30 40 50
40 50
api
worker
batch run
--exclude=api.log
--exclude=worker.log
--exclude=batch run.log
13The space in ${nums[@]: -2} is needed; without it, :- would be read as the "default value" operator. ${logs[@]%.log} strips the suffix from every element, and ${logs[@]/#/--exclude=} replaces the empty string at the start (# anchors to the start) with a prefix, turning a list of names into a list of options. ${#logs[2]} is the length of one element, 13 characters.
Arrays as command lines
The single most practical use of arrays is building up a command's arguments, a few at a time, without quoting bugs. Here's the version people write first, with options in a string:
#!/usr/bin/env bash
# build-tar-string.sh - the same thing with a string (broken)
opts="-czf backup.tar.gz --exclude='*.tmp' --exclude='cache'"
echo "running: tar $opts project"
tar $opts project
tar -tzf backup.tar.gzrunning: tar -czf backup.tar.gz --exclude='*.tmp' --exclude='cache' project
project/
project/README.md
project/cache/
project/cache/page.html
project/src/
project/src/main.sh
project/src/notes.tmp
project/node_modules/
project/node_modules/left-pad/
project/node_modules/left-pad/index.jsThe echoed command looks right, but nothing was excluded. Quotes inside a variable's value are just characters. tar received --exclude='*.tmp' with literal single quotes and excluded files whose names start with a quote. The array version:
#!/usr/bin/env bash
# build-tar-args.sh - build a tar command line in an array
excludes=("*.tmp" "cache" "node_modules")
args=(-czf backup.tar.gz)
if [[ ${VERBOSE:-no} == yes ]]; then
args+=(-v)
fi
for pattern in "${excludes[@]}"; do
args+=("--exclude=$pattern")
done
args+=(project)
echo "running: tar ${args[*]}"
tar "${args[@]}"
tar -tzf backup.tar.gz./build-tar-args.shrunning: tar -czf backup.tar.gz --exclude=*.tmp --exclude=cache --exclude=node_modules project
project/
project/README.md
project/src/
project/src/main.shEach args+=(…) adds exactly one argument, even if it contains spaces or *, and "${args[@]}" hands them to tar intact. Optional flags become a simple if around an append. Use "${args[*]}" only for display, as in the echo line. You'll see this pattern everywhere scripts call rsync, curl, docker run or ssh with conditional options.
Reading into arrays: globs and mapfile
A glob inside array parentheses captures the matching filenames, each as one element:
logs=(logs/*.log)
declare -p logsdeclare -a logs=([0]="logs/api.log" [1]="logs/batch run.log" [2]="logs/worker.log")(With no matches you'd get one element containing the literal pattern, unless nullglob is on, exactly as with for loops.)
mapfile (also spelled readarray) reads lines into an array in one step. Always pass -t, which strips the trailing newline from each element:
mapfile -t hosts < hosts.txt
declare -p hosts
mapfile hosts_raw < hosts.txt
declare -p hosts_rawdeclare -a hosts=([0]="web01" [1]="web02" [2]="db01")
declare -a hosts_raw=([0]=$'web01\n' [1]=$'web02\n' [2]=$'db01\n')Without -t, every element ends in a newline, which breaks comparisons and filenames in confusing ways. Two more options cover most needs: -s N skips the first N lines (a CSV header), and -d '' splits on NUL bytes instead of newlines, which pairs with find -print0 to handle any filename at all:
mapfile -t -s 1 users < users.csv
echo "${#users[@]} users; first: ${users[0]}"
mapfile -d '' -t found < <(find logs -name '*.log' -print0 | sort -z)
printf '[%s]\n' "${found[@]}"3 users; first: asha,asha.k@example.com,platform,yes
[logs/api.log]
[logs/batch run.log]
[logs/worker.log]Feed mapfile with < or < <(command), never with a pipe. A pipe runs it in a subshell (the same trap as while read in the previous article), and the array is thrown away:
cat hosts.txt | mapfile -t piped
echo "piped has ${#piped[@]} elements"piped has 0 elementsAssociative arrays
An associative array maps string keys to values. It must be declared with declare -A before use:
declare -A port
port[http]=80
port[https]=443
port[ssh]=22
echo "${port[https]}"
echo "${!port[@]}"
echo "${port[@]}"
declare -p port443
ssh https http
22 443 80
declare -A port=([ssh]="22" [https]="443" [http]="80" )${!port[@]} gives the keys and ${port[@]} the values. The order is not the insertion order, and you shouldn't rely on any particular order. When output order matters, sort the keys (the counting example below does this).
Looking up a key that doesn't exist returns an empty string, with no error. Test for a key with [[ -v name[key] ]], or supply a default with :-:
[[ -v port[ssh] ]] && echo "ssh is defined"
[[ -v port[ftp] ]] || echo "ftp is not defined"
echo "ftp port: '${port[ftp]}'"
echo "ftp port: ${port[ftp]:-unknown}"
unset 'port[ssh]'
echo "${#port[@]} entries left"ssh is defined
ftp is not defined
ftp port: ''
ftp port: unknown
2 entries leftYou can also fill one in a single statement, which is how you'll usually write lookup tables in scripts:
declare -A limits=([web]=200 [worker]=50 [db]=20)
declare -p limitsdeclare -A limits=([db]="20" [web]="200" [worker]="50" )Forgetting declare -A
This is the associative-array bug everyone hits once. Without declare -A, Bash creates an indexed array and evaluates each "key" as an arithmetic expression. web and db are unset variable names, which evaluate to 0:
colour[web]=green
colour[db]=red
declare -p colourdeclare -a colour=([0]="red")Both assignments went to index 0, and the second overwrote the first. There's no error message. If an associative array seems to hold only one value, check for the missing declare -A with declare -p. Inside a function, declare -A also makes the array local, just like local -A.
Counting with an associative array
Counting occurrences is the classic use. This script counts requests per HTTP status code in an nginx access log, where the status is the ninth whitespace-separated field:
head -n 3 access.log203.0.113.17 - - [09/Nov/2026:08:00:02 +0000] "GET /api/orders/1182 HTTP/1.1" 502 1056 "-" "Mozilla/5.0"
198.51.100.4 - - [09/Nov/2026:08:00:11 +0000] "GET /health HTTP/1.1" 502 3946 "-" "Mozilla/5.0"
203.0.113.17 - - [09/Nov/2026:08:00:20 +0000] "GET /login HTTP/1.1" 200 1722 "-" "Mozilla/5.0"#!/usr/bin/env bash
# status-count.sh [LOG] - count requests per HTTP status code in an nginx access log
declare -A count=()
# Field 9 of the combined log format is the status code.
while read -r _ _ _ _ _ _ _ _ status _; do
count[$status]=$(( ${count[$status]:-0} + 1 ))
done < "${1:-access.log}"
total=0
for code in "${!count[@]}"; do
total=$(( total + ${count[$code]} ))
done
mapfile -t codes < <(printf '%s\n' "${!count[@]}" | sort) # keys come out unordered
for code in "${codes[@]}"; do
pct=$(awk -v c="${count[$code]}" -v t="$total" 'BEGIN { printf "%.1f", c * 100 / t }')
printf '%s %6d %6s%%\n' "$code" "${count[$code]}" "$pct"
done
printf 'all %6d\n' "$total"./status-count.sh access.log
awk '{ print $9 }' access.log | sort | uniq -c200 249 62.2%
301 23 5.8%
304 40 10.0%
404 45 11.2%
500 23 5.8%
502 20 5.0%
all 400
249 200
23 301
40 304
45 404
23 500
20 502The sort | uniq -c pipeline from Searching and Filtering Text confirms the counts. A few details in the script:
readwith nine variable names puts field 9 instatusand the rest of the line in the final_. Repeating_for unwanted fields is a convention, not a keyword.${count[$status]:-0}treats a missing key as 0, so the first occurrence of each code works. The total uses${count[$code]}with a$for the same reason given in the next paragraph.- The percentages come from
awk, because Bash arithmetic is integer-only (covered below).
You'll often see the increment written as (( count[$status]++ )). That's fine for keys you control, like status codes, but the arithmetic context evaluates the key a second time, and a hostile key containing something like $(command) can execute code. For keys that come from untrusted input (URLs, user agents), stick to the explicit form above.
Is a Bash loop the right tool for log analysis? For small files, yes. For big ones, no. On a 50,000-line log on my machine:
wc -l big-access.log
time ./status-count.sh big-access.log > /dev/null
time awk '{ n[$9]++ } END { for (c in n) print c, n[c] }' big-access.log > /dev/null50000 big-access.log
real 0m0.831s
user 0m0.765s
sys 0m0.057s
real 0m0.030s
user 0m0.026s
sys 0m0.004sawk was about 28 times faster, and the gap grows with file size. Every iteration of a Bash loop pays for read, word splitting and variable assignment in an interpreter that was never designed for bulk data; awk is built for exactly this. Use associative arrays for counting things your script encounters (hosts, files, results) and reach for awk to crunch large files.
A config map with defaults
Associative arrays also make a tidy settings store: fill in the defaults, then let a config file override them. This loader rejects unknown keys (typos are a classic source of "my setting is ignored" bugs) and validates a numeric one:
#!/usr/bin/env bash
# load-config.sh FILE - read key = value settings into an associative array over defaults
declare -A config=(
[port]=8080
[workers]=4
[log_level]=info
)
while IFS='= ' read -r key value; do
[[ -z $key || $key == \#* ]] && continue # skip blank lines and comments
if [[ ! -v config[$key] ]]; then
echo "load-config.sh: unknown setting '$key' ignored" >&2
continue
fi
config[$key]=$value
done < "$1"
if [[ ! ${config[workers]} =~ ^[0-9]+$ ]]; then
echo "load-config.sh: workers must be a number, got '${config[workers]}'" >&2
exit 1
fi
for key in $(printf '%s\n' "${!config[@]}" | sort); do
printf '%-10s = %s\n' "$key" "${config[$key]}"
donecat app.conf
./load-config.sh app.conf
./load-config.sh bad.conf; echo "exit $?"# app.conf - overrides for the defaults
port = 9090
log_level = debug
timeout = 30
load-config.sh: unknown setting 'timeout' ignored
log_level = debug
port = 9090
workers = 4
load-config.sh: workers must be a number, got 'four'
exit 1IFS='= ' splits on = and spaces, and because spaces are "whitespace" characters in IFS, the spaces around the = are absorbed into the separator, so port = 9090 gives a clean port and 9090. (The unquoted $(printf … | sort) loop at the end is safe only because the keys are known to contain no spaces.)
Arithmetic with $(( ))
$(( expression )) evaluates integer arithmetic and substitutes the result. Inside it, variables don't need a $, and spaces are allowed anywhere:
echo $(( 7 + 3 * 2 ))
echo $(( (7 + 3) * 2 ))
echo $(( 7 / 2 ))
echo $(( 7 % 2 ))
echo $(( -7 / 2 ))
echo $(( 2 ** 10 ))13
20
3
1
-3
1024Division truncates toward zero: 7 / 2 is 3, and −7 / 2 is −3. That makes the order of operations matter in percentage calculations:
used=937; total=1200
echo "$(( used * 100 / total ))%"
echo "$(( used / total * 100 ))%"78%
0%used / total is 0 in integer math, and 0 × 100 is still 0. Multiply first, then divide.
| Operators | Meaning |
|---|---|
+ - * / % ** | add, subtract, multiply, integer divide, remainder, power |
< <= > >= == != | comparisons: 1 for true, 0 for false |
&& || ! | logical and, or, not |
cond ? a : b | ternary |
= += -= *= /= %= | assignment |
++ -- | increment and decrement |
& | ^ ~ << >> | bitwise and, or, xor, not, shifts |
echo $(( used > 900 ))
echo $(( used > 900 ? 1 : 0 ))
n=7
echo $(( n * 2 )) $(( $n * 2 ))
x=5; (( x += 3 )); echo "$x"1
1
14 14
8Errors and limits are worth seeing once:
echo $(( 10 / 0 ))
echo $(( 2 ** 63 - 1 ))
echo $(( 2 ** 63 ))
echo $(( 1.5 + 1 ))bash: 10 / 0 : division by 0 (error token is "0 ")
9223372036854775807
-9223372036854775808
bash: 1.5 + 1 : syntax error: invalid arithmetic operator (error token is ".5 + 1 ")Numbers are 64-bit signed integers and overflow wraps around silently. There are no decimals at all: 1.5 is a syntax error.
(( )) as a condition, let, and declare -i
Without the leading $, (( expression )) is a command. It evaluates the expression and exits 0 if the result is non-zero, 1 if it is zero. That makes it the natural way to compare numbers in if and while:
(( n > 5 )) && echo "n is greater than 5"
(( n == 7 )); echo "status $?"
(( 0 )); echo "status $?"
if (( used * 100 / total >= 75 )); then echo "over 75% used"; fin is greater than 5
status 0
status 1
over 75% used(( n > 5 )) reads far better than [ "$n" -gt 5 ], and > really means "greater than" here, unlike inside [[ ]].
That "exit 1 when the result is 0" rule has a nasty side effect on increments:
i=0; (( i++ )); echo "status $? i=$i"
i=0; (( ++i )); echo "status $? i=$i"status 1 i=1
status 0 i=1i++ evaluates to the old value, 0, so the command "fails" even though the increment worked. Normally harmless, this kills scripts that use set -e (see Common mistakes). i=$(( i + 1 )) or (( ++i )) avoids it.
let is an older spelling of (( )), and declare -i marks a variable as an integer so every assignment to it is evaluated arithmetically:
let "y = 4 * 5"; echo "$y"
declare -i count=10
count+=5; echo "$count"
count="3 * 4"; echo "$count"
count=abc; echo "$count"
s=10; s+=5; echo "$s"20
15
12
0
105On a normal variable, += appends text (105). On an integer variable it adds. And assigning abc to an integer variable silently gives 0. I don't use declare -i; it makes the meaning of += depend on a declaration that may be far away. $(( )) and (( )) say what they do at the point of use.
Decimals: bc and awk
Bash can't do floating point, so hand decimal math to bc or awk. Both ship with practically every Linux system.
echo "scale=2; 10 / 3" | bc
echo "10 / 3" | bc
echo "scale=1; 937 * 100 / 1200" | bc
awk 'BEGIN { printf "%.1f\n", 937 * 100 / 1200 }'
awk -v u="$used" -v t="$total" 'BEGIN { printf "%.2f%%\n", u * 100 / t }'3.33
3
78.0
78.1
78.08%Two differences: bc defaults to scale=0 (integer results), and it truncates to the scale rather than rounding, which is why it says 78.0 where awk says 78.1 (the exact value is 78.083…). For display, I prefer awk with printf: it rounds, and -v passes shell values in cleanly.
Comparing decimals is the other common need, such as checking the load average against a threshold:
load=$(cut -d ' ' -f1 /proc/loadavg); echo "load: $load"
(( $(echo "$load > 2.5" | bc -l) )) && echo "load is high" || echo "load is normal"
awk -v l="$load" 'BEGIN { exit !(l > 2.5) }' && echo "load is high" || echo "load is normal"load: 10.67
load is high
load is high(The test machine was busy at the time.) bc prints 1 or 0 for a comparison, which (( )) turns into a status. The awk version sets its own exit status: exit !(condition) exits 0 when the condition is true, so it works directly with &&, || and if.
Number bases and the leading-zero trap
$(( )) accepts numbers in other bases with a base# prefix, and C-style 0x (hex) and leading 0 (octal):
echo $(( 16#ff )) $(( 2#1010 )) $(( 8#755 )) $(( 0x1F )) $(( 010 ))
printf '%x %o %d %05.1f\n' 255 493 0x1f 3.14159255 10 493 31 8
ff 755 31 003.1printf goes the other way: %x prints hex and %o octal. 010 being 8 is the trap. Dates and times are full of zero-padded numbers, and date +%m in August prints 08:
month=08
echo $(( month + 1 ))
echo $(( 10#$month + 1 ))bash: 08: value too great for base (error token is "08")
908 is an invalid octal number. Scripts that do arithmetic on months, days, hours or minutes work fine for most of the year and then break in August, September, or after 8 a.m. The fix is the 10# prefix, which forces base 10. Alternatively, ask date for unpadded numbers with %-m.
Special parameters
Bash sets several one-character variables automatically. You've met $?, $#, $@ and $0; here are the rest in one script:
#!/usr/bin/env bash
echo "\$0 script name: $0"
echo "\$\$ PID of this script: $$"
sleep 30 &
echo "\$! PID of the last background job: $!"
kill "$!"
grep -q nosuchuser /etc/passwd
echo "\$? status of the last command: $?"
echo "\$- shell option flags: $-"
ls /etc/hostname > /dev/null
echo "\$_ last argument of the previous command: $_"
( echo "in a subshell: \$\$=$$ BASHPID=$BASHPID" )
echo "main shell: \$\$=$$ BASHPID=$BASHPID"$0 script name: ./special.sh
$$ PID of this script: 29755
$! PID of the last background job: 29756
$? status of the last command: 1
$- shell option flags: hB
$_ last argument of the previous command: /etc/hostname
in a subshell: $$=29755 BASHPID=29760
main shell: $$=29755 BASHPID=29755| Parameter | Value | Typical use |
|---|---|---|
$$ | PID of the shell running the script | unique temp names, PID files, log prefixes |
$! | PID of the most recent background job | kill "$!", wait "$!" |
$? | exit status of the last command | checking results (read it immediately) |
$- | current option flags | [[ $- == *i* ]] tests for an interactive shell |
$_ | last argument of the previous command | interactive shortcut: mkdir newdir && cd "$_" |
BASHPID | PID of the current (sub)shell | differs from $$ inside subshells |
Note that $$ stays the same inside a subshell, while BASHPID changes. At an interactive prompt $- includes i:
echo $-himBHsThe script printed only hB. That i is how ~/.bashrc files detect whether they are being loaded by an interactive shell.
RANDOM and SRANDOM
$RANDOM gives a new integer from 0 to 32767 each time it's read. Assigning to it seeds the generator, which makes the sequence repeatable (handy for tests). $SRANDOM (Bash 5.1+) gives a 32-bit number from the system's secure random source and can't be seeded:
echo $RANDOM $RANDOM $RANDOM
echo $(( RANDOM % 6 + 1 ))
RANDOM=42; echo $RANDOM $RANDOM
RANDOM=42; echo $RANDOM $RANDOM
echo $SRANDOM32021 12785 19568
6
17772 26794
17772 26794
3264065773The everyday use is jitter: when hundreds of machines run the same cron job at 02:00, a random delay spreads the load on whatever they all talk to:
jitter=$(( RANDOM % 30 )); echo "sleeping ${jitter}s before polling"sleeping 25s before pollingRANDOM is fine for jitter, sampling and picking test data. It is not suitable for passwords, tokens or anything security-related; read from /dev/urandom (or use openssl rand) for those.
Where you'll use this
Arrays and arithmetic show up whenever a script collects things and makes decisions on numbers: building rsync or docker argument lists, tallying results across many servers, computing percentages for alerts, enforcing retention counts ("keep the newest 7 backups" is an array slice).
Here is a complete example combining all of it: a disk-usage checker for a monitoring system. It reads df -P output, applies a per-mount warning threshold from an associative array (database volumes are allowed to run fuller than the root filesystem), uses a global critical threshold, collects problems in an indexed array, and exits with the Nagios convention (0 OK, 1 WARNING, 2 CRITICAL):
#!/usr/bin/env bash
# check-disks.sh - check `df -P` output (on stdin) against per-mount thresholds
# Exit codes follow the Nagios convention: 0 OK, 1 WARNING, 2 CRITICAL.
declare -A warn_at=(
[/]=80
[/var/lib/postgresql]=90
)
default_warn=85
crit_at=95
problems=()
worst=0
read -r _header # skip df's header line
while read -r fs _blocks used _avail capacity mount; do
[[ $fs == tmpfs ]] && continue
pct=${capacity%\%} # "84%" -> 84
warn=${warn_at[$mount]:-$default_warn}
used_gib=$(awk -v k="$used" 'BEGIN { printf "%.1f", k / 1048576 }')
if (( pct >= crit_at )); then
problems+=("CRITICAL $mount at $pct% ($used_gib GiB used)")
worst=2
elif (( pct >= warn )); then
problems+=("WARNING $mount at $pct% (threshold $warn%, $used_gib GiB used)")
(( worst < 1 )) && worst=1
fi
done
if (( ${#problems[@]} == 0 )); then
echo "OK: all filesystems below their thresholds"
else
printf '%s\n' "${problems[@]}"
fi
exit "$worst"Reading from stdin makes it easy to test against captured output from a real server as well as live df. Here is a sample in the shape of a database host's df -P output (written by hand, since my test machine has a single nearly empty disk), then the check against it and against my test machine's root filesystem:
cat df-sample.txt
./check-disks.sh < df-sample.txt; echo "exit $?"
df -P / | ./check-disks.sh; echo "exit $?"Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/nvme0n1p2 102626232 86203112 11164052 89% /
/dev/nvme0n1p1 1046508 6248 1040260 1% /boot/efi
tmpfs 8131628 0 8131628 0% /dev/shm
/dev/mapper/data 515010816 491520000 23490816 96% /var/lib/postgresql
/dev/sdb1 983378332 452354048 481000000 49% /srv/backups
WARNING / at 89% (threshold 80%, 82.2 GiB used)
CRITICAL /var/lib/postgresql at 96% (468.8 GiB used)
exit 2
OK: all filesystems below their thresholds
exit 0The pieces map directly onto this article: ${capacity%\%} strips the percent sign so (( )) gets an integer, ${warn_at[$mount]:-$default_warn} is a lookup with a fallback, awk turns KiB into GiB with one decimal, and the problems array collects messages so they can be printed together at the end. The script never builds a string it has to split again. In production you'd run df -P | check-disks.sh from a monitoring agent or a cron job (see System Monitoring and Scheduling with cron and systemd).
Common mistakes
((count++)) kills a script that uses set -e
#!/usr/bin/env bash
set -e
errors=0
echo "counting errors"
((errors++))
echo "errors is now $errors"./errexit-incr.sh; echo "exit $?"counting errors
exit 1The script died silently on its first increment. ((errors++)) evaluated to 0 (the old value), which is a failure status, and set -e exits on failures. Write errors=$(( errors + 1 )) or (( ++errors )). Error Handling, Traps, and Debugging covers set -e and its other surprises.
Using $array when you mean all elements
echo "$servers" prints only element 0, and for s in $servers loops once. Bash gives no warning. Whenever you want the whole array, write "${servers[@]}"; declare -p servers shows you what is actually stored.
An associative array that only ever holds one value
That's a missing declare -A: every string key was evaluated as arithmetic and became index 0. The demonstration is in the associative-arrays section above. Put declare -A name (or local -A name in a function) before the first assignment.
Arithmetic on zero-padded numbers
value too great for base (error token is "08") means a number with a leading zero was read as octal. Prefix the variable with 10# inside $(( )). It's easy to miss in testing because 01 through 07 are valid octal and give the same answer.
Decimals inside $(( ))
syntax error: invalid arithmetic operator (error token is ".5 + 1 ") means a decimal reached Bash arithmetic, often from a load average, a bc result or a version number. Do that calculation in awk or bc, or scale to integers first (work in milliseconds instead of seconds, or percent × 10).
Summary
a=(x y z)creates an indexed array;${a[0]},${a[-1]},${#a[@]}and${!a[@]}give an element, the last element, the count and the indices.$aalone is only element 0, anddeclare -p ashows exactly what's stored.- Always expand with
"${a[@]}"(one word per element). Unquoted${a[@]}re-splits;"${a[*]}"joins with the first character ofIFS. - Build command arguments in an array (
args+=("--exclude=$p"), thencmd "${args[@]}"). Quotes inside a string variable are literal characters and never work. mapfile -t arr < fileandmapfile -t arr < <(command)read lines into an array;-s 1skips a header and-d ''pairs withfind -print0. Never pipe intomapfile.- Associative arrays need
declare -A. Keys are unordered, so sort them for output; test for a key with[[ -v a[key] ]]and use${a[key]:-default}for fallbacks. Count witha[$k]=$(( ${a[$k]:-0} + 1 )). $(( ))is 64-bit integer math: division truncates (multiply before dividing), overflow wraps, decimals are a syntax error.(( expr ))is a condition that succeeds when the result is non-zero, which makes(( i++ ))fail wheniwas 0.- Use
awk(rounds, easyprintfformatting) orbc(truncates toscale) for decimals and decimal comparisons. Force base 10 with10#$varfor zero-padded numbers like months and hours. $$is the script's PID,$!the last background job's PID,$-the shell flags (iwhen interactive), andRANDOMis good for jitter but not for secrets.
Exercises
Create an array of four servers (web01 web02 web03 db01), append cache01, then print the number of servers, the last one, the first three as "the web tier", and the whole list joined with commas.
Show Solution
#!/usr/bin/env bash
servers=(web01 web02 web03 db01)
servers+=(cache01)
echo "count: ${#servers[@]}"
echo "last: ${servers[-1]}"
echo "web tier: ${servers[*]:0:3}"
joined=$(IFS=,; echo "${servers[*]}")
echo "csv: $joined"count: 5
last: cache01
web tier: web01 web02 web03
csv: web01,web02,web03,db01,cache01$( … ) runs in a subshell, so setting IFS inside it doesn't affect the rest of the script, and the joined string is captured in one step.
Write ext-count.sh [DIR] that counts the regular files in DIR by extension, using an associative array, and prints the counts sorted with the most common first (ties alphabetically). Files with no extension, and dotfiles such as .bashrc, count as (none). A name like archive.tar.gz counts as gz.
Hint
${name##*.} removes everything up to the last dot. Turn on dotglob so the glob includes dotfiles, and pipe the finished loop into sort -k1,1nr -k2.
Show Solution
#!/usr/bin/env bash
# ext-count.sh [DIR] - count files per extension
shopt -s nullglob dotglob
declare -A count=()
for path in "${1:-.}"/*; do
[[ -f $path ]] || continue
name=${path##*/}
if [[ $name == *.* && $name != .* ]]; then
ext=${name##*.}
else
ext="(none)"
fi
count[$ext]=$(( ${count[$ext]:-0} + 1 ))
done
for ext in "${!count[@]}"; do
printf '%5d %s\n' "${count[$ext]}" "$ext"
done | sort -k1,1nr -k2ls -A mixed
./ext-count.sh mixed.bashrc Makefile archive.tar.gz data.csv notes.txt old.csv photo.JPG report.csv todo.txt
3 csv
2 (none)
2 txt
1 JPG
1 gzPiping the output of a for loop into sort is fine here because the loop only reads the array; the subshell problem only bites when the loop needs to change variables the rest of the script uses. Extensions are case-sensitive (JPG is not jpg); lowercasing with ${ext,,} would merge them.
Write mem-used.sh [THRESHOLD] that reads MemTotal and MemAvailable from /proc/meminfo, prints the percentage of memory in use with one decimal place plus the used and total amounts in MiB, and exits 1 if usage is above THRESHOLD percent (default 90), 0 otherwise. The threshold comparison must work with decimals.
Show Solution
#!/usr/bin/env bash
# mem-used.sh [THRESHOLD] - memory in use as a percentage with one decimal
threshold=${1:-90}
while read -r key value _; do
case $key in
MemTotal:) total_kb=$value ;;
MemAvailable:) avail_kb=$value ;;
esac
done < /proc/meminfo
used_kb=$(( total_kb - avail_kb ))
pct=$(awk -v u="$used_kb" -v t="$total_kb" 'BEGIN { printf "%.1f", u * 100 / t }')
echo "memory used: $pct% ($(( used_kb / 1024 )) MiB of $(( total_kb / 1024 )) MiB)"
if awk -v p="$pct" -v t="$threshold" 'BEGIN { exit !(p > t) }'; then
echo "above ${threshold}%"
exit 1
fi
echo "below ${threshold}%"./mem-used.sh
./mem-used.sh 5; echo "exit $?"memory used: 32.7% (2568 MiB of 7849 MiB)
below 90%
memory used: 32.9% (2584 MiB of 7849 MiB)
above 5%
exit 1Integer arithmetic is fine for the KiB-to-MiB conversion, where losing the fraction doesn't matter. The percentage and the comparison go through awk because 32.9 would be a syntax error in (( )). Using MemAvailable rather than MemFree matters: Linux uses spare memory for cache, so "free" memory is usually tiny on a healthy machine.
Using access.log from this article, write top-ips.sh [LOG] [N] that counts requests per client IP (the first field) with an associative array and prints the N busiest IPs (default 3), busiest first, as count ip. Check your answer with a sort | uniq -c pipeline.
Show Solution
#!/usr/bin/env bash
# top-ips.sh [LOG] [N] - the N client IPs with the most requests
declare -A hits=()
while read -r ip _; do
hits[$ip]=$(( ${hits[$ip]:-0} + 1 ))
done < "${1:-access.log}"
for ip in "${!hits[@]}"; do
printf '%d %s\n' "${hits[$ip]}" "$ip"
done | sort -rn | head -n "${2:-3}"./top-ips.sh access.log
awk '{ print $1 }' access.log | sort | uniq -c | sort -rn | head -n 3155 203.0.113.17
110 198.51.100.4
52 203.0.113.50
155 203.0.113.17
110 198.51.100.4
52 203.0.113.50Bash can't sort an associative array by value, so the script prints count key pairs and lets sort -rn do the ordering. That split (collect in Bash, sort with sort) is the normal way to rank anything in shell scripts.
Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026, with GNU Awk 5.2.1 and bc 1.07.1. Every command and script above was run as shown, interactively where the examples are interactive. The access logs are synthetic, written by a short awk script using documentation-range IP addresses, and df-sample.txt is a hand-written sample in the format of a database host's df -P output (my test machine only has one nearly empty filesystem); the live df -P / run is shown alongside it. Timings, PIDs, RANDOM values and the load average will differ on your machine.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.