Bash Scripting Patterns for Reusable and Maintainable Code
Functions, parameter expansion, arrays, and traps are the patterns that turn one-off scripts into tools you reuse across projects. Bash scripts grow beyond one-liners when you start reusing logic across projects. The leap from a script that works once to one that works reliably in different contexts comes down to a handful of patterns: functions, parameter expansion, arrays, and traps. After writing and maintaining hundreds of scripts, these are the patterns I reach for repeatedly, and the ones that have saved me the most debugging time. Functions with Local Variables Functions turn a script from a flat sequence of commands into something composable and testable. I define a function for any block of logic I use more than once or that benefits from a descriptive name. The local keyword is essential inside functions because it prevents variables from leaking into the global scope, which is the source of subtle bugs when two functions share a variable name. log() { local level=\ Real-World Lessons I want to share a story from last month that illustrates why this matters more than you might think. A colleague asked me to review their…