Web Analytics

Parameter Expansion

Intermediate ~25 min read

Parameter expansion is one of the most powerful features in Bash. It allows you to transform the value of a variable at the time it is expanded. This is incredibly useful for file path manipulation, setting default values, and cleaning up data.

Removing Patterns

You can remove parts of a string that match a specific pattern. This is often used for file extensions or directory paths.

Syntax Description Mnemonic
${var#pattern} Remove shortest match from beginning # is on the left of $ on US keyboards
${var##pattern} Remove longest match from beginning Double # means "more" removal
${var%pattern} Remove shortest match from end % is on the right of $ on US keyboards
${var%%pattern} Remove longest match from end Double % means "more" removal

Default Values

Bash allows you to provide default values if a variable is unset or empty.

  • ${var:-default}: Use default if var is unset or empty. var remains unchanged.
  • ${var:=default}: Set var to default if it is unset or empty.
Output
Click Run to execute your code
Tip: The pattern matching used here uses "glob" patterns (like * and ?), not regular expressions.

Summary

  • Use # and ## to strip from the start.
  • Use % and %% to strip from the end.
  • Use :- to provide a fallback value without setting the variable.
  • Use := to set a default value if the variable is missing.

What's Next?

In the final lesson of this module, we'll look at Here Documents, a convenient way to handle multi-line text blocks in your scripts.