Arrays and string tricks
A plain variable holds one string. When you have a list (servers, files, packages) you need an array. When you have key → value data, you need an associative array. Bash has both, plus a set of built-in string tools that avoid calling sed and cut for small jobs.
Indexed arrays
servers=("web1" "web2" "db1")
echo "first: ${servers[0]}"
echo "all: ${servers[*]}"
echo "count: ${#servers[@]}"
servers+=("cache1")
servers[1]="web2-new"
echo "now: ${servers[*]}"
echo "last: ${servers[-1]}"
echo "slice: ${servers[*]:1:2}"first: web1 all: web1 web2 db1 count: 3 now: web1 web2-new db1 cache1 last: cache1 slice: web2-new db1
| Syntax | Meaning |
|---|---|
arr=(a b c) |
Create |
${arr[0]} |
One element (counting from 0) |
"${arr[@]}" |
Every element, each kept separate (use this in loops) |
${#arr[@]} |
Number of elements |
arr+=(d) |
Append |
${arr[-1]} |
Last element |
${arr[@]:1:2} |
Two elements starting at index 1 |
unset 'arr[1]' |
Remove an element |
${!arr[@]} |
The indexes |
⚠️ The braces are required:
$servers[0]means "$serversfollowed by the text[0]", and$serversalone is only the first element.
Looping over arrays
files=("report final.pdf" "photo.jpg" "notes.txt")
for f in "${files[@]}"; do
echo "file: $f"
done
for i in "${!files[@]}"; do
echo "$i → ${files[i]}"
donefile: report final.pdf file: photo.jpg file: notes.txt 0 → report final.pdf 1 → photo.jpg 2 → notes.txt
"${files[@]}" (with quotes and @) keeps report final.pdf as one item. It's the array version of "$@".
Filling arrays from commands
mapfile (also called readarray) reads lines into an array, one line per element:
printf "nginx\npostgresql\nredis\n" > packages.txt
mapfile -t pkgs < packages.txt
echo "${#pkgs[@]} packages: ${pkgs[*]}"
mapfile -t big < <(find /etc -maxdepth 1 -name "*.conf" | sort | head -3)
printf "config: %s\n" "${big[@]}"
read -ra words <<< "split these words"
echo "${words[1]}"3 packages: nginx postgresql redis config: /etc/adduser.conf config: /etc/ca-certificates.conf config: /etc/debconf.conf these
-t removes the newline from each line. printf with an array repeats its format for every element, which is a neat way to print lists.
Building command arguments safely
Arrays are the right way to build up a command's options. A string would break on spaces:
opts=(-a -v)
dest="/tmp/my backups"
mkdir -p "$dest" src && touch src/a.txt
opts+=(--exclude "*.tmp")
printf "[%s]\n" rsync "${opts[@]}" src/ "$dest/" # one argument per line[rsync] [-a] [-v] [--exclude] [*.tmp] [src/] [/tmp/my backups/]
Each bracketed line is one argument the command would receive: *.tmp stayed unexpanded and /tmp/my backups/ stayed whole. Run it for real by replacing printf "[%s]\n" with nothing.
Associative arrays (dictionaries)
Declare them with declare -A. Keys are strings:
declare -A ports=([web]=80 [api]=8080 [db]=5432)
ports[cache]=6379
echo "api runs on ${ports[api]}"
echo "${#ports[@]} services"
for name in "${!ports[@]}"; do
echo "$name:${ports[$name]}"
done | sort
if [[ -v ports[db] ]]; then echo "db is configured"; fi
if [[ ! -v ports[queue] ]]; then echo "queue is not configured"; fiapi runs on 8080 4 services api:8080 cache:6379 db:5432 web:80 db is configured queue is not configured
The order of keys in an associative array isn't guaranteed, which is why the loop's output goes through sort.
Counting things
Associative arrays make great counters:
printf "GET\nPOST\nGET\nGET\nDELETE\nPOST\n" > methods.txt
declare -A count
while read -r m; do
(( count[$m]++ ))
done < methods.txt
for m in "${!count[@]}"; do echo "$m ${count[$m]}"; done | sort -k2 -rnGET 3 POST 2 DELETE 1
💡 Associative arrays need Bash 4+. The default
bashon macOS is 3.2; install a newer one withbrew install bash.
String operations
You met ${var#…} and ${var%…} in Quoting and expansion. A few more, all built into Bash:
s="Hello, World"
echo "length: ${#s}"
echo "substring: ${s:7}" # from index 7 to the end
echo "substring: ${s:0:5}" # 5 characters from index 0
echo "last 5: ${s: -5}" # the space before - is required
echo "upper: ${s^^}, lower: ${s,,}"
echo "replace: ${s/World/Bash}"
csv="asha,31,pune"
IFS=, read -r name age city <<< "$csv"
echo "name=$name age=$age city=$city"length: 12 substring: World substring: Hello last 5: World upper: HELLO, WORLD, lower: hello, world replace: Hello, Bash name=asha age=31 city=pune
Trimming and checking
raw=" padded text "
trimmed="${raw#"${raw%%[![:space:]]*}"}"
trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
echo "[$trimmed]"
input="42abc"
if [[ $input =~ ^[0-9]+$ ]]; then echo "number"; else echo "'$input' is not a number"; fi
[[ "hello world" == *world* ]] && echo "contains world"[padded text] '42abc' is not a number contains world
The trimming lines look magical, but they're just "remove the leading spaces" and "remove the trailing spaces" with # and %. When readability matters more than speed, xargs or sed 's/^ *//; s/ *$//' do the same job.
Joining and splitting
parts=("2026" "11" "22")
(IFS=-; echo "${parts[*]}")
path="/usr/local/bin:/usr/bin:/bin"
IFS=: read -ra dirs <<< "$path"
echo "${#dirs[@]} folders on the PATH:"
printf " %s\n" "${dirs[@]}"2026-11-22 3 folders on the PATH: /usr/local/bin /usr/bin /bin
"${arr[*]}" joins the elements with the first character of IFS. Wrapping it in ( ) runs it in a subshell, so the changed IFS doesn't leak into the rest of the script.
printf -v and formatting
printf -v var stores the formatted result in a variable instead of printing it:
printf -v padded "%05d" 42
printf -v stamp "%(%Y)T" -1
echo "$padded"
echo "${#stamp}-digit year"
printf -v row "%-8s|%6.1f%%" "disk" 91.4
echo "[$row]"00042 4-digit year [disk | 91.4%]
%(format)T formats a date without calling date (-1 means "now"). Building strings this way is faster than row=$(printf …), which starts a subshell.
Practice
- Store five server names in an array, then print each with its number:
1) web1. - Read
/etc/passwdinto an array withmapfileand print how many users there are and the last one. - Use an associative array to count how many files of each extension are in a folder.
- Given
url="https://shop.example.com:8443/cart", extract the host and port with${ }or=~.
1.How do you get the number of elements in the array items?
2.Which loop keeps elements with spaces intact?
3.What does declare -A create?