Bash Scripting — Working with Strings

1 minute read

Welcome to Chapter 19 — Working with Strings

Strings are everywhere in shell scripting — filenames, log lines, user input, configuration values, URLs, and more. Bash gives you a surprisingly powerful set of built-in string operations that run without spawning external processes like sed or awk.

In this chapter you’ll learn how to measure, slice, strip, replace, and transform strings using only parameter expansion — one of the most useful (and under-used) features of Bash.


What You’ll Learn

# Topic What It Covers
1 String Length & Empty Checks ${#var}, -z, -n, default values
2 Substring Extraction ${var:offset:length}, negative offsets, basename/dirname tricks
3 Pattern Removal #, ##, %, %% — stripping prefixes & suffixes
4 String Substitution ${var/old/new}, global replace, prefix/suffix replace
5 Case Conversion & Splitting ^^, ,,, IFS splitting, joining arrays
6 Practice Exercises 5 hands-on challenges from easy → advanced

Prerequisites

Before starting this chapter, make sure you’re comfortable with:

  • Variables and quoting — "$var", single vs double quotes
  • Conditionals — if, [[ ]], test operators
  • Functions — basic function syntax and return values
  • Arrays — indexed arrays and "${arr[@]}" expansion

If any of these feel shaky, revisit the earlier chapters first — you’ll get much more out of the exercises that way.


Why Learn Built-in String Operations?

You might wonder: “Why not just use sed, awk, or cut?”

Great question. Here’s why built-in operations matter:

  1. Speed — No subprocess is spawned. Inside a loop processing thousands of lines, the difference is massive.
  2. Portability — Parameter expansion works in every POSIX-compatible shell. External tools may differ across systems.
  3. Readability — Once you know the syntax, ${filename%.csv} is clearer than echo "$filename" | sed 's/\.csv$//'.

That said, external tools still shine for complex multi-line transformations. The key is knowing when each approach fits.


Quick Syntax Cheat Sheet

${#var}              Length of var
${var:offset}        Substring from offset
${var:offset:len}    Substring from offset, len chars
${var#pattern}       Remove shortest prefix match
${var##pattern}      Remove longest prefix match
${var%pattern}       Remove shortest suffix match
${var%%pattern}      Remove longest suffix match
${var/old/new}       Replace first match
${var//old/new}      Replace all matches
${var/#old/new}      Replace prefix
${var/%old/new}      Replace suffix
${var^^}             Uppercase all
${var,,}             Lowercase all
${var^}              Uppercase first char
${var,}              Lowercase first char

Keep this handy as you work through each lesson — you’ll be surprised how often you reach for these.


Let’s Get Started

Head to String Length & Empty Checks to begin.

Happy scripting! 🎯

Updated: