The Bourne Again Shell (bash) performs substitutions in place of special characters, variable names, and commands. Bash performs the substitutions before executing the commands.
The special characters or escape characters are characters that represent special values. These are preceded by a backslash, e.g., \n, \r, etc. The -e option informs the shell to interpret the backslash escape characters.
Character | Description |
\n | new line |
\r | carriage return |
\\ | backslash |
\a | alert (BEL) |
\b | backspace |
\c | suppress trailing newline |
\f | form feed |
\t | horizontal tab |
\v | vertical tab |
Basic variable substitution works by defining a variable and putting the $ sign in front of it. The shell will substitute the variable’s value in place of the name as shown below:
MY_VAR="HELLO WORLD" echo $MY_VAR
You can also use the variable along with other text as follows:
MY_VAR="Apple" echo "There is one $MY_VAR on the floor and two ${MY_VAR}s on the table"
The following table lists all the possibilities of variable substitution:
Form | Description |
${var} | Substitutes the value of var. |
${var:-word} | Substitutes the value of var. If var is NULL or unset, then it substitutes *word* in its place. The value of var does not change. |
${var:=word} | Substitutes the value of var. If var is NULL or unset, then it substitutes *word* in its place and sets var's value equal to *word*. |
${var:?message} | If var is unset or null, it prints out *message* to the standard error. |
${var:+word} | If var is *set*, *word* is substituted in its place. The value of var does not change. |
The shell can execute commands and substitute their output in place of the commands. To use command substitution, we have to put the commands in back quotes.
DATE=`date` echo "Date is $DATE" FILES=`ls | head -5` echo "Files on the directory are $FILES"
RELATED TAGS
CONTRIBUTOR
View all Courses