Advanced Parameter Expansion

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 152 of 205

Parameter expansion is the step in which Bash replaces $name or ${name} with the value of a variable. Lesson 54 introduced the basics, and lesson 45 covered default values such as ${name:-default}. Inside the braces, Bash also offers a small toolkit for changing the value as it is expanded: removing prefixes and suffixes, replacing text, cutting out substrings, changing letter case, looking up a variable whose name is stored in another variable, and transforming a value into a safely quoted form.

All of these operations happen inside the shell. No external program such as sed, cut, basename or tr is started, so they are fast, they work the same on every system that has Bash, and they cannot be confused by unusual characters in the way a pipeline can.

path=/var/www/site/assets/logo.final.png
echo "${path##*/}"      # logo.final.png   (like basename)
echo "${path%/*}"       # /var/www/site/assets   (like dirname)
echo "${path##*.}"      # png   (the extension)

The original variable is never changed by these forms. Each expansion produces a new value, which you can print, compare or assign to another variable.

Overview of the Operators

FormResult
${var#pattern}remove the shortest match of pattern from the start
${var##pattern}remove the longest match from the start
${var%pattern}remove the shortest match from the end
${var%%pattern}remove the longest match from the end
${var/pattern/text}replace the first match
${var//pattern/text}replace every match
${var/#pattern/text}replace a match at the start
${var/%pattern/text}replace a match at the end
${var:offset} / ${var:offset:length}substring
${#var}length in characters
${var^} / ${var^^}first character / all characters to upper case
${var,} / ${var,,}first character / all characters to lower case
${!var}indirect expansion: the value of the variable named by var
${!prefix*} / ${!prefix@}names of all variables starting with prefix
${var@op}transformations: Q, E, A, a, U, u, L, K

Patterns in these forms are glob patterns (lesson 52), not regular expressions: * matches any text, ? one character, and [...] one character from a set.

Removing Prefixes and Suffixes

The four removal operators are the workhorses of parameter expansion. The symbols are easy to remember from a US keyboard: # is to the left of $, so it works on the left (start) of the value, and % is to the right, so it works on the right (end). Doubling the symbol makes the match greedy (longest).

path=/var/www/site/assets/logo.final.png
echo "${path#*.}"     # shortest prefix ending in "."
echo "${path##*.}"    # longest prefix ending in "."
echo "${path%.*}"     # shortest suffix starting with "."
echo "${path%%.*}"    # longest suffix starting with "."
final.png
png
/var/www/site/assets/logo.final
/var/www/site/assets/logo

How the Matching Works

For ${path#*.}, Bash tries prefixes of the value from the shortest upward and stops at the first one that matches *.. The shortest prefix that ends in a dot is /var/www/site/assets/logo., so that part is removed, leaving final.png. For ${path##*.}, Bash looks for the longest matching prefix, /var/www/site/assets/logo.final., leaving only png.

The same logic applies at the end of the value with % and %%. This explains the common idioms:

TaskExpansionResult for logo.final.png
file extension${f##*.}png
name without the last extension${f%.*}logo.final
name without any extension${f%%.*}logo
file name from a path${p##*/}like basename
folder from a path${p%/*}like dirname

If the pattern does not match, the value is returned unchanged, which is usually what you want: ${f##*.} on a name without a dot returns the whole name, so check with [[ $f == *.* ]] first if that matters.

Quoting the Pattern

When the pattern comes from a variable, the quoting decides whether its characters are treated as wildcards or as literal text:

pat="*.txt"
f="a.txt"
echo "${f%$pat} | ${f%"$pat"}"
f2="x*.txt"
echo "${f2%"*.txt"} ${f2%*.txt}"
a | a.txt
x x*

Unquoted, $pat is a pattern: *.txt matches .txt at the end of a.txt. Quoted, it is literal text: a.txt does not end with the characters *.txt, so nothing is removed. For x*.txt, the quoted version removes the literal *.txt and the unquoted version removes just .txt. Quote the pattern whenever it holds user data that must be matched literally.

Search and Replace

The / operators replace the part of the value that matches a pattern:

s="hello world, hello bash"
echo "${s/hello/hi}"      # first match
echo "${s//hello/hi}"     # every match
echo "${s/#hello/HI}"     # only at the start
echo "${s/%bash/zsh}"     # only at the end
echo "${s//o/}"           # delete every "o"
hi world, hello bash
hi world, hi bash
HI world, hello bash
hello world, hello zsh
hell wrld, hell bash

An empty replacement deletes the matches. Because the pattern is a glob, ${s//[0-9]/} deletes every digit and ${s//[^a-z]/} keeps only lower-case letters.

A Practical Use: Making a Slug

A slug is a version of a name that is safe for URLs and file names. Combining case conversion with two replacements produces one without any external tool:

file="My Report (final).PDF"
ext="${file##*.}"
echo "${ext,,} ${file%.*}"
slug="${file,,}"
slug="${slug// /-}"
slug="${slug//[^a-z0-9.-]/}"
echo "$slug"
pdf My Report (final)
my-report-final.pdf

Step by step: ${file,,} makes everything lower case; ${slug// /-} turns spaces into dashes; ${slug//[^a-z0-9.-]/} deletes every character that is not a letter, digit, dot or dash (the parentheses).

Substrings and Length

${var:offset:length} cuts out part of a value. Offsets start at 0. A negative offset counts from the end, and it must be separated from the colon by a space (or put in parentheses), otherwise Bash reads :- as the default-value operator from lesson 45.

s="hello world, hello bash"
echo "${#s}"          # length
echo "${s:6}"         # from position 6 to the end
echo "${s:6:5}"       # 5 characters from position 6
echo "${s: -4}"       # the last 4 characters
echo "${s: -10:5}"    # 5 characters, starting 10 from the end
23
world, hello bash
world
bash
hello

Substrings are useful for fixed-format data such as dates. With d=20261124, the parts are ${d:0:4} (2026), ${d:4:2} (11) and ${d:6:2} (24).

Changing Letter Case

Since Bash 4.0, four operators change letter case:

name="ana maria"
echo "${name^}"       # first character upper case
echo "${name^^}"      # all upper case
up="HELLO"
echo "${up,,} ${up,}" # all lower case / first character lower case
echo "${name^^[am]}"  # only the letters a and m to upper case
Ana maria
ANA MARIA
hello hELLO
AnA MAriA

The optional pattern after the operator limits which characters are converted. A common use is case-insensitive comparison of user answers: if [[ ${answer,,} == y || ${answer,,} == yes ]] accepts Y, yes, YES and Yes alike.

Indirect Expansion and Variable Names

${!name} expands to the value of the variable whose name is stored in name. This lets a script choose a variable at run time:

user_name=ana user_id=1001 user_home=/home/ana
field=user_home
echo "${!field}"
echo "${!user_*}"
/home/ana
user_home user_id user_name

${!user_*} (or ${!user@}, which behaves like "$@" inside double quotes) lists the names of all variables that begin with user_. This makes it easy to print a group of related settings:

for v in "${!user_@}"; do
    printf '%-10s = %s\n' "$v" "${!v}"
done
user_home  = /home/ana
user_id    = 1001
user_name  = ana

For associative arrays, ${!array[@]} has a different meaning: it lists the keys (lesson 103). For a new design, a name reference with declare -n (lesson 104) is usually clearer than ${!name}, but indirect expansion remains common in existing scripts.

Parameter Expansion on Arrays

Every operator in this lesson can be applied to all elements of an array at once by using [@]. The operation runs on each element separately:

arr=(report.txt notes.md data.csv)
echo "${arr[@]%.*}"         # remove each extension
echo "${arr[@]/#/backup_}"  # add a prefix to each element
echo "${arr[@]^}"           # capitalise each element
echo "${#arr[@]} ${#arr[1]}" # number of elements / length of element 1
echo "${arr[@]:1:2}"        # elements 1 and 2 (a slice)
report notes data
backup_report.txt backup_notes.md backup_data.csv
Report.txt Notes.md Data.csv
3 8
notes.md data.csv

${arr[@]/#/backup_} replaces the empty string at the start of each element, which is the standard way to add a prefix. ${arr[@]/%/.bak} adds a suffix in the same way. Note that ${arr[@]:1:2} on an array slices elements, not characters.

Transformation Operators: ${var@op}

Bash 4.4 introduced operators that transform a value in ways that are hard to achieve otherwise. Bash 5.1 added more.

OperatorResultSince
${var@Q}the value quoted so it can be reused as shell input4.4
${var@E}backslash escapes such as \t and \n expanded4.4
${var@A}a declare command that recreates the variable4.4
${var@a}the variable's attribute letters (a array, A associative, i integer, r read-only, x exported)4.4
${var@U} / ${var@u} / ${var@L}upper case / first letter upper case / lower case5.1
${var@K}for arrays, key-value pairs quoted for reuse5.1
str='it'"'"'s a "test"'
echo "${str@Q}"
p='\t tab'
echo "${p@E}"
declare -i num=5
echo "${num@A}"
declare -A cfg=([port]=80 [host]=localhost)
echo "${arr@a} ${cfg@a} ${num@a}"
x="value"
echo "${x@U} ${x@u}"
'it'\''s a "test"'
	 tab
declare -i num='5'
a A i
VALUE Value

@Q is the most useful in practice. It produces text that Bash would read back as exactly the original value, which makes it ideal for log and debug messages: echo "deleting ${file@Q}" shows clearly where a file name begins and ends, even when it contains spaces, quotes or a trailing newline. @A is useful for saving variables to a file that can later be loaded with source (lesson 95).

Combining Expansions

Parameter expansion cannot be nested with one set of braces applied directly to another (${${path##*/}%.*} is an error), but the pattern part of an expansion can itself contain an expansion. This allows a well-known trick for trimming whitespace from both ends of a value:

line="  trim me  "
t="${line#"${line%%[![:space:]]*}"}"   # remove leading whitespace
t="${t%"${t##*[![:space:]]}"}"         # remove trailing whitespace
echo "[$t]"
[trim me]

Read the first line from the inside out: ${line%%[![:space:]]*} removes everything from the first non-space character to the end, which leaves just the leading spaces. That result, quoted so it is taken literally, is then removed from the start of line with #. The second line does the same for the end of the value.

For steps that do not fit in one expansion, use an intermediate variable. It costs nothing and makes the code easier to read:

base=${path##*/}     # logo.final.png
stem=${base%.*}      # logo.final

printf -v (lesson 30) complements parameter expansion for formatting, for example zero-padding a number:

n=7
printf -v padded '%03d' "$n"
echo "$padded"
007

A Complete Example: Parsing URLs Without External Tools

parse-url.sh splits URLs into scheme, user, host, port, path, file name, query string and fragment, using only parameter expansion. It fills in the default port for known schemes, normalises the case of the scheme and host, and reports URLs it cannot parse.

#!/usr/bin/env bash
# parse-url.sh: split URLs into their parts using only parameter expansion
# usage: parse-url.sh URL...
set -u

declare -A default_port=([http]=80 [https]=443 [ftp]=21 [ssh]=22)

parse_url() {
    local url=$1 scheme rest authority userinfo user host port path file query fragment

    if [[ $url != *://* ]]; then
        echo "error: no scheme in '$url'" >&2
        return 1
    fi
    scheme=${url%%://*}
    scheme=${scheme,,}                      # HTTPS -> https
    rest=${url#*://}

    fragment=""
    if [[ $rest == *'#'* ]]; then
        fragment=${rest#*'#'}
        rest=${rest%%'#'*}
    fi
    query=""
    if [[ $rest == *'?'* ]]; then
        query=${rest#*'?'}
        rest=${rest%%'?'*}
    fi

    authority=${rest%%/*}                   # everything before the first /
    if [[ $rest == */* ]]; then
        path=/${rest#*/}
    else
        path=/
    fi

    userinfo=""
    if [[ $authority == *@* ]]; then
        userinfo=${authority%@*}
        authority=${authority##*@}
    fi
    host=${authority%%:*}
    port=""
    [[ $authority == *:* ]] && port=${authority##*:}
    port=${port:-${default_port[$scheme]:-unknown}}

    if [[ -z $host ]]; then
        echo "error: no host in '$url'" >&2
        return 1
    fi

    user=${userinfo%%:*}                    # drop a password after the colon
    file=${path##*/}

    printf '%-9s %s\n' \
        scheme: "$scheme" \
        user: "${user:-(none)}" \
        host: "${host,,}" \
        port: "$port" \
        path: "$path" \
        file: "${file:-(none)}" \
        query: "${query:-(none)}" \
        fragment: "${fragment:-(none)}"
}

status=0
for url in "$@"; do
    echo "== $url"
    parse_url "$url" || status=1
done
exit "$status"

How It Works

A URL has the general shape scheme://user:password@host:port/path?query#fragment, and the function peels it apart from the outside in:

  • ${url%%://*} removes the longest suffix starting with ://, leaving the scheme; ${scheme,,} makes it lower case. ${url#*://} removes the scheme and ://, leaving the rest.
  • The fragment is removed first, because it is the last part and may itself contain ? or /. ${rest#*'#'} keeps what follows the first #, and ${rest%%'#'*} keeps what comes before it. The # is quoted so that it is not read as the # operator.
  • The query is handled the same way with ?, which is quoted because an unquoted ? is a wildcard for one character.
  • ${rest%%/*} keeps everything before the first slash, the "authority" part (user:password@host:port). If a slash exists, ${rest#*/} gives the path, and a missing path becomes /.
  • ${authority%@*} and ${authority##*@} split off the user information at the last @, so a password containing @ is still handled. ${userinfo%%:*} keeps only the user name, so the password is never printed.
  • ${authority%%:*} gives the host and ${authority##*:} the port. ${port:-${default_port[$scheme]:-unknown}} uses nested defaults: an explicit port first, then the scheme's usual port from the associative array, then unknown.
  • ${host,,} normalises the host name, because host names are not case-sensitive.
  • ${path##*/} extracts the file name, and ${file:-(none)} shows a placeholder when the path ends in /.
  • status records whether any URL failed, so the script exits with 1 if at least one could not be parsed.

This parser deliberately handles common URLs only. It does not decode percent-encoded characters such as %20, and it does not understand IPv6 addresses in brackets.

Running the Complete Example

./parse-url.sh 'HTTPS://Ana:secret@Example.COM:8443/docs/guide.html?lang=en&v=2#install' \
    'http://example.com' 'ftp://files.example.org/pub/' \
    'example.com/page' 'https:///nohost' 'gopher://old.example.net:70'
echo "status $?"
== HTTPS://Ana:secret@Example.COM:8443/docs/guide.html?lang=en&v=2#install
scheme:   https
user:     Ana
host:     example.com
port:     8443
path:     /docs/guide.html
file:     guide.html
query:    lang=en&v=2
fragment: install
== http://example.com
scheme:   http
user:     (none)
host:     example.com
port:     80
path:     /
file:     (none)
query:    (none)
fragment: (none)
== ftp://files.example.org/pub/
scheme:   ftp
user:     (none)
host:     files.example.org
port:     21
path:     /pub/
file:     (none)
query:    (none)
fragment: (none)
== example.com/page
error: no scheme in 'example.com/page'
== https:///nohost
error: no host in 'https:///nohost'
== gopher://old.example.net:70
scheme:   gopher
user:     (none)
host:     old.example.net
port:     70
path:     /
file:     (none)
query:    (none)
fragment: (none)
status 1

The first URL exercises every part: the upper-case scheme and host were normalised, the password secret was dropped, and the query and fragment were separated correctly. The plain http://example.com received port 80 from the defaults table and the path /. The two malformed URLs produced clear errors and made the final status 1, while the gopher URL, which is not in the defaults table, worked because it gave its port explicitly. The URLs are in single quotes on the command line because &, ? and # are special characters to the shell (lesson 47).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Advanced Parameter Expansion and get answers drawn from it.

Signed-in readers only.