Guide Bash-Scripting Beginner

Strings

String concatenation, length, substring extraction, case conversion, splitting, and comparison in Bash.

3 min read

Concatenation

FIRST="Hello"
SECOND="World"
GREETING="$FIRST $SECOND"          # simple concatenation via adjacency
GREETING="${FIRST}, ${SECOND}!"      # braces make boundaries explicit
GREETING+=" — Bash"                    # append with +=

Length & Substrings

STR="Kubernetes"
echo "${#STR}"          # 10 — length

echo "${STR:0:4}"         # "Kube" — substring: start at 0, length 4
echo "${STR:4}"             # "rnetes" — from index 4 to the end
echo "${STR: -4}"             # "etes" — last 4 characters (note the required space before -4)

Case Conversion (Bash 4+)

STR="Hello World"
echo "${STR,,}"       # "hello world" — lowercase everything
echo "${STR^^}"         # "HELLO WORLD" — uppercase everything
echo "${STR^}"            # "Hello World" — capitalize first character only

Search & Replace

STR="production-app-v1"
echo "${STR/app/service}"     # "production-service-v1" — replace FIRST match
echo "${STR//-/_}"               # "production_app_v1" — replace ALL matches ("//" = global)
echo "${STR#*-}"                    # "app-v1" — strip shortest match from front
echo "${STR##*-}"                     # "v1" — strip LONGEST match from front (greedy)
echo "${STR%-*}"                        # "production-app" — strip shortest match from back

Splitting a String

CSV="alice,bob,carol"
IFS=',' read -ra NAMES <<< "$CSV"
for name in "${NAMES[@]}"; do
    echo "Name: $name"
done

# Alternative using tr
echo "$CSV" | tr ',' '\n'

Trimming Whitespace

STR="   padded value   "
TRIMMED="${STR#"${STR%%[![:space:]]*}"}"    # trim leading
TRIMMED="${TRIMMED%"${TRIMMED##*[![:space:]]}"}"   # trim trailing
echo "[$TRIMMED]"

# Simpler in practice: use xargs (also collapses internal whitespace)
echo "   padded value   " | xargs

String Comparison

A="hello"
B="world"

if [ "$A" = "$B" ]; then echo "equal"; else echo "not equal"; fi
if [[ "$A" == h* ]]; then echo "starts with h"; fi     # [[ ]] supports pattern matching
if [ -z "$A" ]; then echo "empty"; fi                    # -z tests for empty string
if [ -n "$A" ]; then echo "not empty"; fi                  # -n tests for non-empty

Checking If a String Contains a Substring

STR="deploying to production"
if [[ "$STR" == *"production"* ]]; then
    echo "This is a production deploy!"
fi

if echo "$STR" | grep -q "production"; then
    echo "Found via grep"
fi

Production Considerations

  • Always quote string comparisons ([ "$A" = "$B" ]) — an unquoted, empty $A collapses the test into invalid syntax and a confusing error.
  • Prefer [[ ]] over [ ] for string pattern matching and logical operators in Bash-only scripts — it’s safer and more capable, but not POSIX/sh-portable.
  • ${STR,,}/${STR^^} require Bash 4+ — on macOS’s default (very old) bash 3.2, use tr '[:upper:]' '[:lower:]' instead for portability.

Quick Interview Answer

“Bash handles strings through parameter expansion: ${STR:start:len} for substrings, ${STR/old/new} for replace-first and ${STR//old/new} for replace-all, ${STR,,}/${STR^^} for case conversion, and ${#STR} for length. [[ "$STR" == *pattern* ]] checks substring containment, and IFS=',' read -ra ARR <<< "$STR" splits a delimited string into an array.”

Common Mistakes

  • Using == for equality in [ ] (POSIX test) instead of = — works in bash but isn’t portable to strict sh.
  • Forgetting the required space in ${STR: -4} (negative substring index) — ${STR:-4} means something completely different (a default value expansion).
  • Not quoting string variables in comparisons, breaking on empty or space-containing values.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form