In Bash, expansion refers to the process where specific characters or patterns are replaced with actual values before executing a command. This feature allows users to efficiently handle file paths, arithmetic calculations, and generate multiple text strings dynamically.
This article explores various types of expansion, including pathname expansion, tilde expansion, arithmetic expansion, and brace expansion.
Pathname Expansion (*, ?, [])
Pathname expansion is used when working with wildcards to match file names.
Example: Expanding * to List Files
echo *
Output (lists all files in the current directory):
bash
Desktop Documents Pictures Videos
Similarly, we can match specific patterns:
echo D*
Output:
bash
Desktop Documents
Handling Hidden Files in Expansion
By default, hidden files (starting with .) are excluded from expansions. Using .* will show hidden files but also include . (current directory) and .. (parent directory):
ls -d .* | less
A better approach:
echo .[!.]*
This lists only hidden files, excluding . and ... Alternatively, ls -A provides an accurate list:
ls -A
Tilde Expansion (~)
The tilde ~ represents the home directory of a user.
Example: Expanding ~ for Current User
echo ~
Output:
bash
/home/user
For another user, prepend the username:
echo ~foo
Output:
bash
/home/foo
Arithmetic Expansion ($((...)))
Arithmetic expansion enables basic calculations within the shell.
Example: Basic Arithmetic
echo $((2 + 2))
Output:
bash
4
Supported operators:
Operator | Description |
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Integer division |
% | Modulo (remainder) |
** | Exponentiation |
Example using exponentiation and multiplication:
echo $(((5**2) * 3))
Output:
bash
75
Since floating-point arithmetic is not supported, results are rounded down:
echo $((5 / 2))
Output:
bash
2
Brace Expansion ({}) for Generating Multiple Text Strings
Brace expansion generates multiple variations of a string dynamically.
Example: Expanding a Text Pattern
echo Front-{A,B,C}-Back
Output:
bash
Front-A-Back Front-B-Back Front-C-Back
Numbers can also be generated in sequences:
echo Number_{1..5}
Output:
bash
Number_1 Number_2 Number_3 Number_4 Number_5
For zero-padded numbers (Bash 4.0+):
echo {01..15}
Output:
bash
01 02 03 04 05 ... 15
Letters can also be expanded in reverse order:
echo {Z..A}
Output:
bash
Z Y X ... B A
Using Brace Expansion to Create Directories
Brace expansion is useful for bulk directory creation. Example: Organizing photos by year and month:
mkdir Photos cd Photos mkdir {2007..2009}-{01..12}
Generated directories:
bash
2007-01 2007-02 ... 2009-12
Bash provides powerful mechanisms for handling variables, dynamic command execution, and controlling text interpretation. These mechanisms include:
Parameter Expansion – Accesses stored variables dynamically.
Command Substitution – Uses command output as input.
Quoting Techniques – Controls how Bash interprets special characters.
This article explores how to work with variables, command substitution, and different quoting techniques to manage command execution efficiently.
Parameter Expansion ($VAR)
Parameter expansion allows users to retrieve the values of stored variables.
Example: Expanding $USER to Show Username
echo $USER
Output:
bash
me
To view all available system variables, use:
printenv | less
If a variable does not exist, expansion returns an empty string:
echo $SUER
Output:
bash
(empty)
Command Substitution ($(COMMAND))
Command substitution allows users to execute a command and use its output as an argument or variable.
Example: Listing Files Using Command Substitution
echo $(ls)
Output (lists all files in the current directory):
bash
Desktop Documents Pictures Videos
Example: Using which to Find cp and Pass It to ls
ls -l $(which cp)
This finds the full path of cp and displays details using ls.
Example: Using Pipelines in Command Substitution
Command substitution supports pipelines:
file $(ls -d /usr/bin/* | grep zip)
This filters zip-related files and passes results to file for analysis.
Alternative Syntax Using Backticks
Older syntax for command substitution uses backticks () instead of$()**:
ls -lwhich cp
Though supported, **using$()` is recommended for better readability.
Quoting Techniques
Quoting helps control how Bash processes special characters and expansions.
Example: Word Splitting Without Quotes
echo this is a test
Output:
bash
this is a test
Here, spaces are treated as word separators, splitting the text into multiple arguments.
Example: Using Quotes to Preserve Spaces
echo "this is a test"
Now, spaces are retained within the argument, treating it as a single string.
Handling Special Characters in Quotes
Using double quotes (" ") prevents word splitting, pathname expansion, and brace expansion, but allows parameter, arithmetic, and command substitution.
Example: Protecting Variable Expansion with Quotes
echo "The total is $100.00"
Without quotes, $1 is undefined, resulting in incorrect output:
bash
The total is 00.00
Using quotes ensures proper interpretation of text.
Effect of Quotes on Command Substitution
Command substitution treats spaces and newlines differently when enclosed in quotes.
Example: Running cal Without Quotes
echo $(cal)
Output (spaces removed, formatted into a single line):
bash
February 2020 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 ... 28 29
Example: Running cal With Quotes
echo "$(cal)"
Output (preserving newlines and spaces):
bash
February 2020
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 ... 28 29
Here, quotes ensure output formatting remains intact.
Introduction
Understanding single quotes (' '), escaping characters (\), and special backslash sequences in Bash allows users to properly manage text interpretation, variable expansions, and control character behavior in scripts and commands. These tools help ensure that special characters are correctly handled in filenames, variables, and command execution.
This article explains how single quotes suppress expansions, how escaping prevents unintended behavior, and how control sequences modify text output.
Using Single Quotes (' ')
Single quotes completely suppress all expansions, including variable substitution, command substitution, arithmetic expansion, and wildcard interpretation.
Comparison of Unquoted, Double Quotes, and Single Quotes
Unquoted: Expansions occur normally.
echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER
Output:
bash
text /home/me/ls-output.txt a b foo 4 me
Double Quotes: Some expansions are preserved, but pathname and brace expansion are suppressed.
echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER"
Output:
bash
text ~/*.txt {a,b} foo 4 me
Single Quotes: All expansions are completely suppressed.
echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER'
Output:
bash
text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER
This ensures exactly what is typed is displayed, with no interpretation.
Escaping Characters (\)
The escape character (\) allows specific characters to be treated literally, preventing their special behavior. Common use cases include:
Preventing variable substitution
Escaping special characters in filenames
Ensuring special symbols are interpreted correctly
Example: Escaping $ to Prevent Variable Expansion
echo "The balance for user $USER is: $5.00"
Output:
bash
The balance for user me is: $5.00
Without escaping, $5.00 would be interpreted as an undefined variable ($5), producing incorrect output.
Example: Escaping Special Characters in Filenames
mv bad\&filename good_filename
Since & normally has special meaning in Bash, escaping ensures it is treated as a normal character in the filename.
Escaping the Backslash (\) Itself
To include a literal \, escape it using \\:
echo "Backslash: \\"
Output:
bash
Backslash: \
Within single quotes, \ loses its special meaning and is treated as a normal character.
Backslash Escape Sequences for Control Codes
The first 32 ASCII characters transmit commands to terminal-like devices, some of which are commonly used in scripting.
Common Escape Sequences
Escape Sequence | Meaning |
\a | Bell (causes computer to beep) |
\b | Backspace |
\n | Newline (line feed) |
\r | Carriage return |
\t | Tab |
Escape sequences originated from C programming and are widely used in shell scripting.
Using Escape Sequences in echo
To interpret escape sequences in echo, use -e or $' ' syntax.
Example: Creating a Countdown Timer with sleep and \a
sleep 10; echo -e "Time's up\a"
Alternatively:
sleep 10; echo "Time's up" $'\a'
Upon execution, the terminal beeps after 10 seconds using \a.