Parameter Expansion Basics

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 54 of 205

Parameter expansion is the part of Bash that replaces $name with the value of a variable, and it can do much more than that. Inside the braces form ${...} you can ask for a variable's length, cut out part of its value, remove a prefix or suffix, replace text, and change letter case, all without starting another program. This lesson covers the everyday operations. A later lesson covers the advanced ones.

Understanding the Concept

A parameter is anything that holds a value: a variable such as name, a positional parameter such as 1, a special parameter such as #, or an array element. Writing $name asks Bash to put the value in place. Writing ${name} does the same, and ${name...} with an operator after the name asks Bash to transform the value first.

Two facts to keep in mind throughout:

  • The expansion produces text. It does not change the variable itself, unless the operator is one of the assignment forms such as ${var:=value}.
  • The result is subject to word splitting and filename expansion if it is not quoted, like any other expansion.
t="one fish two fish"
echo "${t/fish/cat}"
echo "$t"

Output:

one cat two fish
one fish two fish

The first command printed a changed copy. The variable t still holds the original text.

Braces Around Variable Names

The braces tell Bash exactly where the variable name ends. They are optional when the character after the name cannot be part of a name, and required when it can:

name="Ada"
echo "$nameLovelace|"
echo "${name}Lovelace"
echo "${name}_report"
echo "$name_report|"

Output:

|
AdaLovelace
Ada_report
|

Variable names may contain letters, digits and underscores. Bash read $nameLovelace as a variable of that whole name, which is unset, so the first line printed only the bar. With braces the name stops at }.

Positional parameters need braces once they pass nine:

set -- a b c d e f g h i j k l
echo "$10"
echo "${10}"
echo "${11}"

Output:

a0
j
k

$10 means $1 followed by the character 0, which printed a0. ${10} is the tenth parameter.

String Length

${#name} gives the number of characters in the value:

word="programming"
echo "${#word}"
empty=""
echo "${#empty}"
unset gone
echo "${#gone}"

Output:

11
0
0

An empty variable and an unset one both have length 0. The # has a second use with arrays and positional parameters: ${#arr[@]} is the number of elements, ${#arr[2]} is the length of one element, and ${#} or ${#@} is the number of positional parameters.

arr=(x yy zzz)
echo "${#arr[@]}"
echo "${#arr[2]}"
set -- a b c
echo "${#}"

Output:

3
3
3

The length counts characters or bytes, depending on the locale. For the word café, which contains one accented letter that takes two bytes in UTF-8, the result was 5 in the plain C locale and 4 with LC_ALL=C.UTF-8.

Extracting a Substring

${name:offset:length} returns part of the value, starting at offset (counting from 0) and taking length characters:

s="Hello, World"
echo "${s:7}"
echo "${s:0:5}"
echo "${s:7:3}"

Output:

World
Hello
Wor
  • ${s:7} has no length, so it takes everything from position 7 to the end.
  • ${s:0:5} takes five characters from the start.
  • ${s:7:3} starts at position 7 and takes three.

A negative offset counts from the end. It must be separated from the colon by a space or placed in parentheses, because :- means something else:

echo "${s: -5}"
echo "${s: -5:3}"
echo "${s:-5}"

Output:

World
Wor
Hello, World

${s:-5} is the "use a default value" operator from the earlier lesson on default values: s is set, so its value was printed unchanged. The offset and length can be arithmetic: ${s:off:5} and ${s:$((off-7)):5} both work. A length longer than the remaining text simply stops at the end, and an offset past the end gives an empty result.

Removing a Prefix or Suffix

Four operators cut text off the beginning or the end of a value by matching a pattern (a glob pattern, not a regular expression):

OperatorMeaning
${var#pattern}Remove the shortest match 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

A way to remember them: # appears before a number on a keyboard and works on the front, while % appears after a number and works on the back. Doubling the symbol means "longest".

p="/home/ana/docs/report.final.txt"
echo "${p#*/}"
echo "${p##*/}"
echo "${p#/home/}"
echo "${p#x}"

Output:

home/ana/docs/report.final.txt
report.final.txt
ana/docs/report.final.txt
/home/ana/docs/report.final.txt
  • */ matches "anything up to a slash". The shortest match is just the leading /, so # removed only that.
  • With ##, the longest match is everything up to the last slash, leaving the file name.
  • A pattern that does not match removes nothing, as ${p#x} shows.

The same idea works from the end:

echo "${p%.*}"
echo "${p%%.*}"
echo "${p%/*}"
echo "${p%.txt}"
echo "${p%.csv}"

Output:

/home/ana/docs/report.final
/home/ana/docs/report
/home/ana/docs
/home/ana/docs/report.final
/home/ana/docs/report.final.txt

Taking File Names Apart

With a name that has more than one dot, the short and long forms give different pieces:

file="archive.tar.gz"
echo "name: ${file%%.*}"
echo "everything after the first dot: ${file#*.}"
echo "last extension: ${file##*.}"
echo "without last extension: ${file%.*}"

Output:

name: archive
everything after the first dot: tar.gz
last extension: gz
without last extension: archive.tar

For paths, ${p##*/} does what basename does, and ${p%/*} does what dirname does, without starting a program:

p=/var/log/syslog.1
echo "${p##*/} / $(basename "$p")"
echo "${p%/*} / $(dirname "$p")"

Output:

syslog.1 / syslog.1
/var/log / /var/log

One difference to know: when the value has no slash, ${bare%/*} returns the value unchanged, because nothing matched, while dirname returns ..

Replacing Text

${var/pattern/replacement} replaces the first match of the pattern. A second slash at the front replaces every match:

FormEffect
${var/pat/rep}Replace the first match
${var//pat/rep}Replace all matches
${var/#pat/rep}Replace a match at the start
${var/%pat/rep}Replace a match at the end
${var//pat}Delete all matches
t="one fish two fish red fish"
echo "${t/fish/cat}"
echo "${t//fish/cat}"
echo "${t/#one/ONE}"
echo "${t/%fish/bird}"
echo "${t//fish}"

Output:

one cat two fish red fish
one cat two cat red cat
ONE fish two fish red fish
one fish two fish red bird
one  two  red 

The pattern accepts wildcards:

echo "${t/f?sh/X}"
echo "${t//[aeiou]/_}"

Output:

one X two fish red fish
_n_ f_sh tw_ f_sh r_d f_sh

To replace a slash, escape it so Bash does not take it for the end of the pattern:

slash="/usr/local/bin"
echo "${slash//\//:}"
path_dots="a.b.c"
echo "${path_dots//./-}"

Output:

:usr:local:bin
a-b-c

The Ampersand in Bash 5.2

In Bash 5.2 and later, an unquoted & in the replacement stands for the text that was matched. This is the patsub_replacement option, on by default. Use a backslash to get a literal ampersand:

x=abc
echo "${x/b/[&]}"
echo "${x/b/[\&]}"

Output:

a[b]c
a[&]c

In the pattern itself, an ampersand is an ordinary character, so ${amp/&/and} turns Tom & Jerry into Tom and Jerry.

Changing Letter Case

Bash can change case with four operators. A single symbol changes the first character, and a doubled symbol changes every character:

FormEffect
${var^}First character to upper case
${var^^}All characters to upper case
${var,}First character to lower case
${var,,}All characters to lower case
m="hello World"
echo "${m^}"
echo "${m^^}"
echo "${m,,}"
echo "${m,}"

Output:

Hello World
HELLO WORLD
hello world
hello World

An optional pattern restricts which characters change:

echo "${m^^[a-e]}"

Output:

hEllo WorlD

Only the letters from a to e were changed to upper case, which affected the e in "hello" and the d in "World".

Patterns Stored in Variables

The pattern part can come from a variable. When it is unquoted, its wildcard characters work. When it is quoted, they are taken literally:

suffix=".txt"
fn="notes.txt"
echo "${fn%$suffix}"

sv="xaXXbz"
star="a*b"
echo "${sv/$star/Q}"
echo "${sv/"$star"/Q}"

Output:

notes
xQz
xaXXbz

The unquoted $star acted as the pattern a*b, which matched aXXb. The quoted "$star" was the literal text a*b, which does not occur in xaXXbz.

Applying Expansions to Many Values

On positional parameters and arrays, the operators apply to each element:

set -- apple banana cherry
echo "${@/a/A}"
echo "${@:2}"
echo "${1^^}"

fruit=(apple banana cherry)
echo "${fruit[@]^^}"
echo "${fruit[1]:0:3}"
echo "${fruit[@]%e}"

Output:

Apple bAnana cherry
banana cherry
APPLE
APPLE BANANA CHERRY
ban
appl banana cherry

${@:2} takes every parameter from the second onwards, which is the same offset idea as for strings. ${fruit[@]%e} removed a trailing e from each element separately; only apple ended in e.

Practical Applications

Changing File Extensions

for f in *.jpeg; do echo "$f -> ${f%.jpeg}.jpg"; done

Output (in a folder with a.jpeg and b.jpeg):

a.jpeg -> a.jpg
b.jpeg -> b.jpg

Replacing echo with mv "$f" "${f%.jpeg}.jpg" would perform the rename. Run the echo version first to check the names.

Formatting Text

user=ada
echo "Hello, ${user^}!"
t="my report final.txt"
echo "${t// /_}"

Output:

Hello, Ada!
my_report_final.txt

Testing Extensions

for f in report.txt data.csv; do
  case $f in
    *.txt) echo "${f%.txt} is text";;
    *.csv) echo "${f%.csv} is csv";;
  esac
done

Output:

report is text
data is csv

Availability in Other Shells

The operators ${#var}, #, ##, % and %% are part of the POSIX standard and work in Dash:

sh -c 'v=report.txt; echo "${v%.txt}"; echo "${v#rep}"; echo "${#v}"'

Output:

report
ort.txt
10

Substrings, replacement and case changes are Bash features. Dash rejects them:

sh -c 'v=hello; echo "${v^^}"'

Output:

sh: 1: Bad substitution

A script that starts with #!/bin/sh should therefore use only the first group, or call sed, tr and similar programs instead. Other expansions, such as indirect expansion with ${!name}, are covered in the lesson on advanced parameter expansion.

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 Parameter Expansion Basics and get answers drawn from it.

Signed-in readers only.