Parameter expansion is a powerful feature available in the bash shell of Linux that allows you to manipulate the values of variables. With a bit of practice, it can become an essential tool in your command-line toolkit, useful for tasks such as defaulting values and string manipulation. Below are several examples to illustrate its functionality.
Basic Usage
You can use parameter expansion to include the value of a variable within a string. For instance:
$ name="Bozo"$ echo "Hello, ${name}!"Hello, Bozo!
In this example, ${name}
expands to the value of the variable name
.
Default Values
You can set a default value if a variable isn’t defined or is null:
$ echo "${name:-Guest}" # Uses "name" if set, otherwise "Guest"Guest
Further, you can assign a default while checking if a variable is already set:
$ echo ${MYID-anonymous} # Uses MYID if set, otherwise "anonymous"anonymous
Using a similar notation, you can assign a default if necessary:
$ echo ${var:=NOT_SET}123456789$ echo ${var2:=NOT_SET}NOT_SET
Displaying Variable Length
To determine the length of a variable’s value, use:
$ var="bananas"$ echo ${#var}7
Substring Extraction
You can also extract substrings from a variable:
$ var="123456789"$ echo ${var:1:3}234$ echo ${var:0:3}123
Remove Parts of Strings
You can remove specified text from the beginning or end of a variable’s value:
$ file="archive.tar.gz"$ echo ${file%.gz} # Removes .gzarchive.tar$ echo ${file%%.*} # Removes everything after the first stringarchive
Pattern Matching
You can manipulate strings by removing patterns:
$ text="You can be whatever you want to be"$ echo ${text#You} # Removes "You" from the startcan be whatever you want to be$ echo ${text//be/do} # Replaces all instances of "be" with "do"You can do whatever you want to do
Indirect Expansion
You can even have variables point to other variables:
name="user"user="Sandra"echo ${!name} # Expands to the value of "user"Sandra
Conclusion
Parameter expansion is a versatile feature that, once mastered, enhances your command-line capabilities significantly. Practice using these examples, and you’ll find many situations where they can simplify your tasks on a Linux system.