Built.io Blog

Parameter Expansions in BASH

,

The simplest parameter expansion is ${parameter}.

a=”Hello ”
echo ${a}world
Hello world

You'll see that “${...}” causes the parameters to expand. In the above case, it’s variable a that expands. However, echo $aworld will return null because it's a variable without any values set.

Setting default values

The parameter expansions can be typically used when defining variables which accept value as a command line argument, such as:

file_path=$1

Here, the file_path variable receives a value of the first command line argument that's passed. It's easy to verify the value:

if [ -n “$file_path” ]; then
    echo “$file_path is not empty.”
else
    echo “File path is empty.”
fi

The logic of the bash script gets divided into an if-else statement, whether or not any useful logic resides under the ‘else’ part. This can be avoided using expansions, allowing a default value to be set for a particular variable:

file_path=${1:-some_default_path}

Even if the first argument is null, the file_path variable will hold a stipulated default value.

String manipulations

a=”abc def”
echo ${a^}      #Capitalizes the string - only first character
echo ${a^^}     #Case change for all characters -- To uppercase
echo ${a~}      #Lowercase first letter
echo ${a~~}     #Lowercase all letters

Indirect expansion

If you need to use the value of a variable which is evaluated from another variable, indirect expansion is useful:

a=”abc”
abc=5
echo ${!a}
5

Arithmetic expressions

$(( … )) allows arithmetic expressions to be evaluated.
echo $(( 3 + 2 ))
5

More advanced parameter expansions can be used to find and replace a pattern in strings. This can be used for easy filename manipulation and more. For more information, visit wiki.bash-hackers.org/.

Subscribe to our blog