Parameter Expansion on Linux
Parameter expansion can seem a bit challenging at first, but once you become familiar with its syntax and applications, it can be incredibly useful for manipulating variable values in various ways, whether in shell scripts or directly on the command line.
Basic Usage
A simple instance of parameter expansion returns the greeting “Hello” combined with the value of a variable:
$ name="Bozo"$ echo "Hello, ${name}!"Hello, Bozo!
You can also set default values if a variable is not defined or is empty. For example:
$ echo "${name:-Guest}" # If "name" isn't set, it will output "Guest"Guest
This command displays the value of the variable MYID, defaulting to “anonymous” if MYID isn’t set:
$ echo ${MYID-anonymous}anonymous
In different cases, using := will assign a value if it hasn’t been defined:
$ echo ${var:=NOT_SET}123456789$ echo ${var2:=NOT_SET}NOT_SET
Checking Values
You can print a message and exit if a variable is not set or is null using this syntax:
$ echo "${HOSTNAME:?HOSTNAME is not set}"fedora$ echo "${HOSTNAME2:?HOSTNAME2 is not set}"-bash: HOSTNAME2: HOSTNAME2 is not set
Measuring Length
To determine the length of a variable’s value, use:
$ var="bananas"$ echo ${#var}7
Extracting Substrings
You can also extract substrings using defined positions:
$ var="123456789"$ echo ${var:1:3}234$ echo ${var:0:3}123
In another example, extracting a substring:
$ text="I love Linux"$ echo ${text:7:5}Linux
Modifying Variables
To remove certain patterns from the variable:
$ file="archive.tar.gz"$ echo ${file%.gz} # Removes the ".gz" extensionarchive.tar$ echo ${file%%.*} # Removes everything after the first dotarchive
You can also manipulate strings to replace specific instances of text:
$text="You can be whatever you want to be"$ echo ${text/be/do} # Changes the first instance onlyYou can do whatever you want to be$ echo ${text//be/do} # Changes all instancesYou can do whatever you want to do
Indirect Expansion
Creating indirect expansions allows a variable to reference another variable:
name="user"user="Sandra"echo ${!name} Sandra
Conclusion
Parameter expansion may require some practice, but mastering it will greatly enhance your efficiency and versatility when working in a Linux environment.
Welcome to DediRock, your trusted partner in high-performance hosting solutions. At DediRock, we specialize in providing dedicated servers, VPS hosting, and cloud services tailored to meet the unique needs of businesses and individuals alike. Our mission is to deliver reliable, scalable, and secure hosting solutions that empower our clients to achieve their digital goals. With a commitment to exceptional customer support, cutting-edge technology, and robust infrastructure, DediRock stands out as a leader in the hosting industry. Join us and experience the difference that dedicated service and unwavering reliability can make for your online presence. Launch our website.