Start Coding

Topics

Bash Parameter Expansion

Bash parameter expansion is a powerful feature that allows you to manipulate and transform variable values in shell scripts. It provides a concise way to modify strings, set default values, and perform various operations on variables without external commands.

Basic Syntax

The general syntax for parameter expansion is:

${parameter}

Where "parameter" can be a variable name, a special shell parameter, or an expression.

Common Use Cases

1. Default Values

Set a default value if a variable is unset or null:

${variable:-default_value}

Example:

echo ${name:-"Guest"}
# Output: Guest (if name is unset)

2. String Manipulation

Perform operations like substring extraction or replacement:

${string:position:length}  # Substring extraction
${string/pattern/replacement}  # Pattern replacement

Example:

text="Hello, World!"
echo ${text:7:5}  # Output: World
echo ${text/World/Bash}  # Output: Hello, Bash!

3. Length of a Variable

Get the length of a variable's value:

${#variable}

Example:

name="John Doe"
echo ${#name}  # Output: 8

Advanced Parameter Expansion

1. Removing Prefixes and Suffixes

Remove matching patterns from the beginning or end of a string:

${variable#pattern}  # Remove shortest matching prefix
${variable##pattern}  # Remove longest matching prefix
${variable%pattern}  # Remove shortest matching suffix
${variable%%pattern}  # Remove longest matching suffix

Example:

file="script.tar.gz"
echo ${file#*.}  # Output: tar.gz
echo ${file##*.}  # Output: gz
echo ${file%.*}  # Output: script.tar
echo ${file%%.*}  # Output: script

2. Case Modification

Change the case of variable values:

${variable^}  # Capitalize first character
${variable^^}  # Convert to uppercase
${variable,}  # Lowercase first character
${variable,,}  # Convert to lowercase

Example:

text="hello WORLD"
echo ${text^}   # Output: Hello WORLD
echo ${text^^}  # Output: HELLO WORLD
echo ${text,}   # Output: hello WORLD
echo ${text,,}  # Output: hello world

Best Practices

  • Use parameter expansion for simple string manipulations to improve script performance.
  • Enclose variable names in curly braces {} to avoid ambiguity, especially when concatenating with other text.
  • Combine parameter expansion with Bash quoting to handle variables with spaces or special characters.
  • Use parameter expansion in conjunction with Bash conditional expressions for more complex logic in your scripts.

Conclusion

Bash parameter expansion is a versatile feature that enhances your ability to work with variables efficiently. By mastering these techniques, you can write more concise and powerful shell scripts. Remember to consult the Bash manual for a complete list of parameter expansion options and their specific behaviors.

For more advanced scripting techniques, explore Bash command substitution and Bash process substitution.