Bash Bash Parameter Expansion

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

The $ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

Read more in the Bash User Manual.

Syntax

  • ${parameter:offset} # Substring starting at offset
  • ${parameter:offset:length} # Substring of length "length" starting at offset
  • ${#parameter} # Length of parameter
  • ${parameter/pattern/string} # Replace the first occurrence of pattern with string
  • ${parameter//pattern/string} # Replace all occurrences of pattern with string
  • ${parameter/#pattern/string} # Replace pattern with string if pattern is at the beginning
  • ${parameter/%pattern/string} # Replace pattern with string if pattern is at the ending
  • ${parameter#pattern} # Remove shortest match of pattern from beginning of parameter
  • ${parameter##pattern} # Remove longest match of pattern from beginning of parameter
  • ${parameter%pattern} # Remove shortest match of pattern from end of parameter
  • ${parameter%%pattern} # Remove longest match of pattern from end of parameter
  • ${parameter:-word} # Expand to word if parameter unset/undefined
  • ${parameter:=word} # Expand to word if parameter unset/undefined and set parameter
  • ${parameter:+word} # Expand to word if parameter set/defined


Got any Bash Question?