typestar

Parameter expansion in Bash

The brace toolkit: length, trims, defaults and substitution.

file="report.draft.txt"

echo "${#file} characters"          # length
echo "${file%.txt}"                 # strip the shortest suffix match
echo "${file%%.*}"                  # strip the longest suffix match
echo "${file#report.}"              # strip a prefix

# defaults: use a fallback without touching the variable
echo "${EDITOR_CHOICE:-nano}"
echo "${file/draft/final}"          # substitution
echo "${file^^}"                    # uppercase

How it works

  1. ${#file} is length; % and # trim suffixes and prefixes.
  2. :- supplies a default without touching the variable.
  3. ${file/draft/final} substitutes; ^^ uppercases.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
448
Tokens
61
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 2 of 3 in Variables & quoting, step 2 of 26 in Language basics.

← Previous Next →