Manipulate strings without leaving Bash — length, slicing, search-and-replace, and case conversion — and store lists of values in indexed and associative arrays.
Why: Bash can inspect and cut strings using parameter expansion, no external tools needed. ${#var} is the length. ${var:start:len} extracts a substring (positions count from 0).
#!/usr/bin/env bash
s="deployment"
echo "${#s}" # 10 (length)
echo "${s:0:6}" # deploy (from 0, take 6)
echo "${s:6}" # ment (from 6 to the end)Why: ${var/old/new} replaces the first match; ${var//old/new} replaces every match. This is the quick way to swap or strip parts of a string inside a script.
#!/usr/bin/env bash
path="src/app/main.js"
echo "${path/.js/.ts}" # src/app/main.ts (first match)
echo "${path//\//-}" # src-app-main.js (all slashes -> dashes)Why: ${var#pattern} trims a matching prefix, ${var%pattern} trims a matching suffix — the everyday way to split a filename from its extension or a path from its basename. Double the symbol (## or %%) for the longest match.
#!/usr/bin/env bash
file="archive.tar.gz"
echo "${file%.gz}" # archive.tar (drop shortest suffix)
echo "${file%%.*}" # archive (drop longest suffix)
echo "${file#*.}" # tar.gz (drop shortest prefix)Why: ${var^^} upper-cases and ${var,,} lower-cases — handy for normalizing user input before comparing it, so "YES", "Yes", and "yes" all match.
#!/usr/bin/env bash
read -r -p "Continue? " answer
case "${answer,,}" in # lower-case the input first
y|yes) echo "going ahead" ;;
*) echo "stopping" ;;
esacWhy: an array holds a list of values under one name. Build one with ( ), read an element with ${arr[i]} (counting from 0), and expand the whole list with "${arr[@]}". ${#arr[@]} is the element count.
#!/usr/bin/env bash
servers=("web1" "web2" "db1")
echo "${servers[0]}" # web1
echo "count: ${#servers[@]}" # 3
servers+=("cache1") # append
for s in "${servers[@]}"; do
echo "host: $s"
doneWhy: an associative array maps string keys to values, like a dictionary. Declare it with declare -A first. Use them for lookups — a port per service, a count per word. Note: this needs Bash 4+ (run `bash --version` to check).
#!/usr/bin/env bash
declare -A port
port[web]=80
port[ssl]=443
echo "web runs on ${port[web]}" # 80
# Iterate keys and values
for svc in "${!port[@]}"; do
echo "$svc -> ${port[$svc]}"
done