Parameter Expansion Default And Substitute
Use bash parameter expansion for default values, substring extraction, and pattern removal in a single script.
Code
#!/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: 13What 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.