Scripts constantly handle lists (servers, files, regions) and chop up strings (strip a file extension, pull a version out of a tag, upper-case an environment name). You could call sed or cut for every one of those, but Bash has fast, built-in tools for both: arrays and parameter expansion. This lesson covers the ones you will actually use.
In simple words
- Array: one variable that holds a list of values.
- Associative array: a list of key=value pairs, like a small dictionary.
- Parameter expansion: built-in tricks like
${file%.log}that cut, replace or change text without extra programs.
Indexed arrays
An array holds an ordered list of values in one variable:
hosts=(web1 web2 db1)echo "${hosts[0]}"echo "${hosts[2]}"echo "${hosts[@]}"echo "${#hosts[@]}"web1db1web1 web2 db13| Syntax | Meaning |
|---|---|
arr=(a b c) | create |
${arr[0]} | one element (indexes start at 0) |
${arr[-1]} | the last element |
"${arr[@]}" | every element, each as a separate word |
${#arr[@]} | number of elements |
${!arr[@]} | the indexes |
arr+=(d e) | append |
${arr[@]:1:2} | a slice: 2 elements starting at index 1 |
unset 'arr[1]' | remove one element |
The braces are required: $hosts[0] means "$hosts followed by the text [0]".
Add and loop:
hosts+=(cache1)for h in "${hosts[@]}"; do echo "-> $h"; doneecho "last: ${hosts[-1]}"echo "middle two: ${hosts[@]:1:2}"-> web1-> web2-> db1-> cache1last: cache1middle two: web2 db1Why "${arr[@]}" with quotes
Like "$@", the quoted form keeps each element intact, even if it contains spaces:
files=("app.log" "error log.txt")for f in "${files[@]}"; do echo "[$f]"; donefor f in ${files[@]}; do echo "[$f]"; done[app.log][error log.txt][app.log][error][log.txt]Arrays are also the safest way to build a command with optional arguments:
args=(--namespace "$ns" --timeout 60s)[[ $dry_run == 1 ]] && args+=(--dry-run=client)kubectl apply -f deploy.yaml "${args[@]}"Building the same thing in a string and running it unquoted breaks the moment a value has a space.
Filling an array from a command
mapfile (also called readarray) reads lines into an array, one element per line:
mapfile -t names < <(cut -d: -f1 /etc/passwd)echo "${#names[@]} users, first is ${names[0]}, last is ${names[-1]}"7 users, first is root, last is postgres-t removes the newline from each line. Do not write names=($(cut …)): that splits on spaces and expands globs, the same bug as looping over $(ls).
Associative arrays (maps)
An associative array maps names to values, like a dictionary. Declare it with declare -A first:
declare -A port=([web]=80 [api]=8080 [db]=5432)echo "api listens on ${port[api]}"port[cache]=6379for svc in "${!port[@]}"; do echo "$svc -> ${port[$svc]}"; done | sortapi listens on 8080api -> 8080cache -> 6379db -> 5432web -> 80${!port[@]} gives the keys. The order of keys is not guaranteed, which is why the output is piped through sort. Check whether a key exists with [[ -v port[web] ]].
A practical use: counting things.
declare -A countwhile read -r ip _; do count[$ip]=$(( ${count[$ip]:-0} + 1 )); done < /var/log/nginx/access.logfor ip in "${!count[@]}"; do echo "${count[$ip]} $ip"; done | sort -rn4 10.0.0.53 10.0.0.72 10.0.0.92 10.0.0.121 10.0.0.21String length and substrings
tag="release-2.4.1"echo "${#tag}"echo "${tag:8}"echo "${tag:0:7}"132.4.1release${var:offset:length} takes a substring; leave out the length to go to the end.
Removing a prefix or suffix
These four are the workhorses of path and version handling:
| Syntax | Removes | Greedy? |
|---|---|---|
${var#pattern} | shortest match from the start | no |
${var##pattern} | longest match from the start | yes |
${var%pattern} | shortest match from the end | no |
${var%%pattern} | longest match from the end | yes |
A memory trick: # is on the left of $ on a US keyboard (start), % is on the right (end).
path=/var/backups/db-2026-11-29.tar.gzecho "${path##*/}"echo "${path%/*}"file=${path##*/}echo "${file%.tar.gz}"echo "${file%%.*}"echo "${file#*.}"db-2026-11-29.tar.gz/var/backupsdb-2026-11-29db-2026-11-29tar.gz${path##*/} is a built-in basename and ${path%/*} a built-in dirname, without starting a new process.
Search and replace
msg="deploy to staging, then staging again"echo "${msg/staging/prod}"echo "${msg//staging/prod}"image="registry.local/team/api:1.4"echo "${image%:*}:1.5"deploy to prod, then staging againdeploy to prod, then prod againregistry.local/team/api:1.5One slash replaces the first match; two slashes replace all. Anchor with # or %: ${v/#http:/https:} replaces only at the start.
Changing case
env=prodecho "${env^^}"name=LEELAecho "${name,,}"word=checkoutecho "${word^}"PRODleelaCheckout^^ upper-cases everything, ,, lower-cases everything, and a single ^ or , changes only the first letter. This is very handy for normalising user input before a case statement.
Splitting a string into parts
To split on a character, set IFS for one read and read into an array:
version=2.4.1IFS=. read -r major minor patch <<< "$version"echo "major=$major minor=$minor patch=$patch"echo "next minor: $major.$((minor + 1)).0"major=2 minor=4 patch=1next minor: 2.5.0<<< is a here-string: it feeds a string to a command's input. You will meet it again in lesson 9.
Real-world scenario: bump a version and tag an image
A release job reads the current version from a git tag, bumps the patch number, and builds the new image name, all without calling sed, cut or awk:
last_tag="v2.4.9"ver=${last_tag#v}IFS=. read -r ma mi pa <<< "$ver"new="v$ma.$mi.$((pa + 1))"repo="registry.local/shop/checkout"echo "next tag: $new"echo "image: $repo:${new#v}"next tag: v2.4.10image: registry.local/shop/checkout:2.4.10Note that string comparison would have gone wrong here: as text, 9 sorts after 10. Splitting into numbers and using arithmetic gives the right answer.
Common mistakes
- Missing braces:
$arr[1]is$arrplus the text[1]. Write${arr[1]}. - Unquoted
${arr[@]}: elements with spaces are split. arr=($(command)): splits on spaces and expands*. Usemapfile -t arr < <(command).- Forgetting
declare -A: without it,m[web]=80treatswebas arithmetic (0) and creates an indexed array. - Mixing up
#and%, or forgetting that doubling them makes the match greedy. - Relying on key order of associative arrays.
Practice
- Create an array of four regions, print how many there are, the first and the last.
- Use
mapfileto load the second column of/etc/hostsinto an array and print it joined with commas (hint:IFS=,; echo "${arr[*]}"). - Given
url=https://api.example.com/v1/orders, print just the hostapi.example.comusing only parameter expansion. - Build an associative array that counts how many users in
/etc/passwduse each shell. - Turn
my-service_NAMEintoMY-SERVICE-NAME.
Cheat sheet
a=(x y z) a+=(w) create, append${a[0]} ${a[-1]} element, last element"${a[@]}" ${#a[@]} all elements, count${!a[@]} indexes or keysmapfile -t a < <(cmd) lines into arraydeclare -A m=([k]=v) associative array${#s} ${s:2:3} length, substring${s#p} ${s##p} strip from start (short, long)${s%p} ${s%%p} strip from end (short, long)${s/a/b} ${s//a/b} replace first, all${s^^} ${s,,} ${s^} upper, lower, capitaliseIFS=. read -r a b c <<< "$v" splitKey takeaways
- Arrays hold lists safely; always expand them as
"${arr[@]}". - Fill arrays from commands with
mapfile -t, neverarr=($(…)). declare -Acreates maps for lookups and counting.#,##,%,%%strip prefixes and suffixes;/and//replace;^^and,,change case.- Built-in expansions are faster and safer than piping every string through
sedorcut.