Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Intermediate

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

bash
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}"
Output
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 "$servers followed by the text [0]", and $servers alone is only the first element.

Looping over arrays

bash
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]}"
done
Output
file: 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:

bash
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]}"
Output
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:

bash
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
Output
[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:

bash
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"; fi
Output
api 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:

bash
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 -rn
Output
GET 3
POST 2
DELETE 1

💡 Associative arrays need Bash 4+. The default bash on macOS is 3.2; install a newer one with brew install bash.

String operations

You met ${var#…} and ${var%…} in Quoting and expansion. A few more, all built into Bash:

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"
Output
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

bash
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"
Output
[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

bash
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[@]}"
Output
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:

bash
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]"
Output
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

  1. Store five server names in an array, then print each with its number: 1) web1.
  2. Read /etc/passwd into an array with mapfile and print how many users there are and the last one.
  3. Use an associative array to count how many files of each extension are in a folder.
  4. Given url="https://shop.example.com:8443/cart", extract the host and port with ${ } or =~.
✎ Check your understanding

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?

← Functions