Linux Basic — Working with Strings

1 minute read

Working with Strings

Almost every Bash script ends up massaging strings: extracting a filename from a path, stripping an extension, replacing tokens in a template, converting case, or splitting on a delimiter. Bash has first-class string operations built right into parameter expansion — no sed, no awk, no fork. Once you learn the syntax it feels like magic.

This chapter covers the complete native toolkit.


What You Will Learn

By the end of this chapter you will be able to:

  • Measure string length and check for emptiness with ${#var}, -z, -n
  • Use parameter defaults: ${var:-x}, ${var:=x}, ${var:?msg}, ${var:+x}
  • Extract substrings with ${var:offset:length} and negative offsets
  • Remove prefixes/suffixes with #, ##, %, %% — including basename / dirname without forking
  • Substitute text with ${var/old/new} and ${var//old/new}
  • Convert case with ${var^^}, ${var,,}
  • Split on a delimiter with IFS=… read -ra arr

Topics in This Chapter

# Topic Description
1 String Length & Empty Checks ${#var}, -z/-n, parameter defaults
2 Substring Extraction ${var:off:len} slicing
3 Pattern Removal Strip prefix/suffix with # ## % %%
4 String Substitution ${var/old/new} and ${var//old/new}
5 Case Conversion & Splitting ^^, ,,, and IFS=… read -ra
6 Practice Exercises Hands-on tasks

Why This Matters — Speed

A naive script for the question “what is the basename of /var/log/nginx/access.log?”:

# ❌ Spawns a process every call
name=$(basename "$path")

The native equivalent:

# ✅ Zero forks — pure parameter expansion
name=${path##*/}

Run that in a 100,000-iteration loop and the difference is two minutes vs two milliseconds. That’s why parameter expansion is the foundation of every fast Bash script.


Next → String Length & Empty Checks

Updated: