Przejdลบ do treล›ci

๐Ÿง  Parameter Expansion

Parameter expansion is one of the most powerful features of POSIX shells. It enables variable substitution, default values, substring extraction, pattern removal, and error handling โ€” all without invoking external tools.


๐ŸŽ“ Who This Is For

  • Engineers writing productionโ€‘grade shell scripts
  • DevOps/SRE teams optimizing automation performance
  • Developers replacing external tools (sed, cut, awk) with builtโ€‘in expansions
  • Anyone needing predictable, portable string manipulation in POSIX shells

๐Ÿงฉ Role in the Ecosystem

Parameter expansion is a core part of the POSIX shell execution model. It provides:

  • Fast, builtโ€‘in string manipulation
  • Portable alternatives to external commands
  • Error handling for required variables
  • Safe defaults for unset or empty parameters
  • A foundation for writing robust scripts

It is supported by all POSIX shells (dash, ash, ksh, bash in POSIX mode).


๐Ÿงฉ Key Concepts

1. Default and Fallback Values

1
2
echo "${VAR:-fallback}"   # use fallback if VAR is unset or empty
echo "${VAR:=default}"    # assign default if VAR is unset or empty

2. Required Variables

1
: "${TOKEN:?TOKEN is required}"

3. Substring Extraction

1
2
3
name="robert"
echo "${name:0:3}"        # rob
echo "${name:2}"          # bert

4. String Length

1
echo "${#name}"           # 6

5. Pattern Removal

1
2
3
path="/var/log/nginx/access.log"
echo "${path%/*}"         # /var/log/nginx
echo "${path##*/}"        # access.log

6. Indirection (bash/ksh)

1
2
3
var="TARGET"
TARGET="value"
echo "${!var}"            # value

๐Ÿ”ง Notable Techniques

Prefix/Suffix Removal

1
2
3
file="backup_2025.tar.gz"
echo "${file#backup_}"    # 2025.tar.gz
echo "${file%.gz}"        # backup_2025.tar

Patternโ€‘Based Replacement (bash/ksh)

1
2
text="a b c"
echo "${text// /_}"       # a_b_c

Safe Variable Expansion

1
echo "${VAR:-}"           # expands to empty string if unset

Numeric Expansion (bash/ksh)

1
2
num=5
echo "$(( num + 1 ))"     # 6

โš ๏ธ Limitations & Pitfalls

  • Some expansions are not POSIX (e.g., ${var//pattern/repl})
  • Dash/ash do not support substring syntax ${var:offset:length}
  • Indirection ${!var} is bash/kshโ€‘only
  • Pattern matching uses shell globs, not regex
  • Quoting rules can change expansion behavior
  • Expansion inside double quotes preserves whitespace; unquoted does not

๐Ÿง  When to Use Parameter Expansion

  • Replacing external tools for performance
  • Writing portable /bin/sh scripts
  • Validating required variables
  • Manipulating paths, filenames, and strings
  • Ensuring predictable behavior in CI/CD pipelines

โŒ When Not to Use Parameter Expansion

  • When complex parsing is required (use awk or a real language)
  • When portability across nonโ€‘POSIX shells is uncertain
  • When readability suffers due to overly dense expansions

โœ… Best Practices

  • Prefer parameter expansion over external tools for simple operations
  • Use ${var:?message} for required variables
  • Use ${var:-} to avoid unbound variable errors
  • Quote expansions unless intentional:
1
echo "$var"
  • Avoid bashโ€‘only expansions in /bin/sh scripts
  • Test expansions under multiple shells (bash, dash, ash, ksh)

๐Ÿงช Testing Parameter Expansion

1
2
3
4
5
set -x
VAR=""
echo "${VAR:-fallback}"
echo "${VAR:=default}"
echo "${#VAR}"

Test portability:

1
2
3
dash script.sh
bash --posix script.sh
ksh script.sh

๐Ÿง  Summary

Parameter expansion is a fast, portable, and powerful mechanism for manipulating variables in POSIX shells. It replaces many external tools, improves performance, and enables robust error handling โ€” making it essential for productionโ€‘grade scripting.