Parameter Expansion Default And Substitute

Use bash parameter expansion for default values, substring extraction, and pattern removal in a single script.

BashConfig Management

Code

bashsnippet
14 lines
#!/usr/bin/env bash
set -euo pipefail

INPUT="${1:-default_value}"
SUFFIX="${2:-txt}"

echo "Input: ${INPUT}"
echo "First 4 chars: ${INPUT:0:4}"

FILENAME="archive.tar.gz"
echo "Without extension: ${FILENAME%%.*}"
echo "Last extension: ${FILENAME##*.}"
echo "Upper: ${INPUT^^}"
echo "Length: ${#INPUT}"

Output

Captured from a sandboxed run of this snippet in the build pipeline.

Input: default_value
First 4 chars: defa
Without extension: archive
Last extension: gz
Upper: DEFAULT_VALUE
Length: 13

What the code does

set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.

The script leans on parameter expansion 8 times, using forms like ${var:-default}, ${var##prefix}, ${var%%suffix} so defaults, trimming, and casing happen inside the shell with no external tool.

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.