String Operators
The curly-bracket syntax allows for the shell’s string operators. String operators allow you to manipulate values of variables in various useful ways without having to write full-blown programs or resort to external UNIX utilities. You can do a lot with string-handling operators even if you haven’t yet mastered the programming features we’ll see in later chapters.
In particular, string operators let you do the following:
Ensure that variables exist (i.e., are defined and have non-null values)
Set default values for variables
Catch errors that result from variables not being set
Remove portions of variables’ values that match patterns
Syntax of String Operators
The basic idea behind the syntax of string operators is that special characters that denote operations are inserted between the variable’s name and the right curly bracket. Any argument that the operator may need is inserted to the operator’s right.
The first group of string-handling operators tests for the existence of variables and allows substitutions of default values under certain conditions. These are listed in Table 4.1. [51]
Table 4-1. Substitution Operators
| Operator | Substitution |
|---|---|
| $ { varname :- word } |
If varname exists and isn’t null, return its value; otherwise return word. |
| Purpose: |
Returning a default value if the variable is undefined. |
| Example: |
${count:-0} evaluates to 0 if count is undefined. |
| $ { varname := word} |
If varname exists and isn’t null, return its value; otherwise set it to word |