Substitution operators

Substitution operators are used for expanding parameters and variable values.


${variablename:-some word}

-If varname exists and isn’t null, return its value; otherwise return word.

Purpose: Returning a default value if the variable is undefined.

[root@euve59329 ~]# echo ${PWDx:-non existent variable}
non existent variable

– If varname exists and isn’t null, return its value; otherwise set it to
word and then return its value. Positional and special parameters

[root@euve59329 ~]# echo ${ID:=0}

– ID variable does not exist. In this case, the value is set to 0.

Purpose:Setting a variable to a default value if it is undefined.


If varname exists and isn’t null, return its value; otherwise print
varname: followed by message, and abort the current command or
script (non-interactive shells only). Omitting message produces the
default message parameter null or not set.


[root@euve59329 ~]# echo ${thevariable:?does not exist}
bash: thevariable: does not exist
[root@euve59329 ~]#

– Purpose: Catching errors that result from variables being undefined.


[root@euve59329 ~]# echo ${count:+1}
[root@euve59329 ~]# echo ${countX:+1}

Purpose: Testing for the existence of a variable.
Example: ${count:+1} returns 1 (which could mean “true”) if count is




Performs substring expansion.[5] It returns the substring of $varname
starting at offset and up to length characters. The first character in
$varname is position 0. If length is omitted, the substring starts at
offset and continues to the end of $varname. If offset is less than 0 then
the position is taken from the end of $varname. If varname is @, the
length is the number of positional parameters starting at parameter
Purpose: Returning parts of a string (substrings or slices).


[root@euve59329 ~]# count=MyCoolText
[root@euve59329 ~]# echo ${count:4}
[root@euve59329 ~]# echo ${count:4:4}
[root@euve59329 ~]#

Inspired from Learning the bash Shell: Unix Shell Programming (In a Nutshell (O’Reilly))

Posted in BASH. Tagged with , , .

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.