Skip to content
$ lynuxpro
← Bash Scripting

LESSON 7 OF 17 · INTERMEDIATE · 18 MIN

Arrays and string manipulation

HOW IT WORKSArrays and parameter expansion

hosts=(web1 web2 db1)indexed array"${hosts[@]}"every element${#hosts[@]}count = 3file=app-2026.tar.gza string${file%%.*}app-2026${file#*.}tar.gz${s//old/new}replace
1/4

An array holds many values in one variable. Expand all of them safely with "${hosts[@]}".

for h in "${hosts[@]}"; do echo "$h"; done

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[@]}"
SHELLbashutf-8 · 5L
web1db1web1 web2 db13
OUTPUTterminalutf-8 · 4L
SyntaxMeaning
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}"
SHELLbashutf-8 · 4L
-> web1-> web2-> db1-> cache1last: cache1middle two: web2 db1
OUTPUTterminalutf-8 · 6L

Why "${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
SHELLbashutf-8 · 3L
[app.log][error log.txt][app.log][error][log.txt]
OUTPUTterminalutf-8 · 5L

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[@]}"
SHELLbashutf-8 · 3L

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]}"
SHELLbashutf-8 · 2L
7 users, first is root, last is postgres
OUTPUTterminalutf-8 · 1L

-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 | sort
SHELLbashutf-8 · 4L
api listens on 8080api -> 8080cache -> 6379db -> 5432web -> 80
OUTPUTterminalutf-8 · 5L

${!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 -rn
SHELLbashutf-8 · 3L
4 10.0.0.53 10.0.0.72 10.0.0.92 10.0.0.121 10.0.0.21
OUTPUTterminalutf-8 · 5L

String length and substrings

tag="release-2.4.1"echo "${#tag}"echo "${tag:8}"echo "${tag:0:7}"
SHELLbashutf-8 · 4L
132.4.1release
OUTPUTterminalutf-8 · 3L

${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:

SyntaxRemovesGreedy?
${var#pattern}shortest match from the startno
${var##pattern}longest match from the startyes
${var%pattern}shortest match from the endno
${var%%pattern}longest match from the endyes

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#*.}"
SHELLbashutf-8 · 7L
db-2026-11-29.tar.gz/var/backupsdb-2026-11-29db-2026-11-29tar.gz
OUTPUTterminalutf-8 · 5L

${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"
SHELLbashutf-8 · 5L
deploy to prod, then staging againdeploy to prod, then prod againregistry.local/team/api:1.5
OUTPUTterminalutf-8 · 3L

One 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^}"
SHELLbashutf-8 · 6L
PRODleelaCheckout
OUTPUTterminalutf-8 · 3L

^^ 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"
SHELLbashutf-8 · 4L
major=2 minor=4 patch=1next minor: 2.5.0
OUTPUTterminalutf-8 · 2L

<<< 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}"
SHELLbashutf-8 · 7L
next tag: v2.4.10image:    registry.local/shop/checkout:2.4.10
OUTPUTterminalutf-8 · 2L

Note 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 $arr plus the text [1]. Write ${arr[1]}.
  • Unquoted ${arr[@]}: elements with spaces are split.
  • arr=($(command)): splits on spaces and expands *. Use mapfile -t arr < <(command).
  • Forgetting declare -A: without it, m[web]=80 treats web as 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

  1. Create an array of four regions, print how many there are, the first and the last.
  2. Use mapfile to load the second column of /etc/hosts into an array and print it joined with commas (hint: IFS=,; echo "${arr[*]}").
  3. Given url=https://api.example.com/v1/orders, print just the host api.example.com using only parameter expansion.
  4. Build an associative array that counts how many users in /etc/passwd use each shell.
  5. Turn my-service_NAME into MY-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"   split
OUTPUTterminalutf-8 · 12L

Key takeaways

  • Arrays hold lists safely; always expand them as "${arr[@]}".
  • Fill arrays from commands with mapfile -t, never arr=($(…)).
  • declare -A creates 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 sed or cut.