Command substitution
Command substitution means that the shell can execute commands first, save the output temporarily, and output it where appropriate.
Syntax for command substitution:
' Command '
Note that it is an anti-quote , not a single quote, which is below the ESC key .
In the following example, the command execution results are saved in a variable:
#!/bin/bashdate = ' date ' who | WC -l ' echo " up = ' date ; uptime echo " uptime is $UP
Operation Result:
Variable substitution
Variable substitution can change its value depending on the state of the variable (whether it is empty, whether it is defined, etc.)
Variable substitution forms that you can use:
form |
Description |
${var} |
The variable's original value |
${var:-word} |
If the variable var is empty or has been deleted (unset), then return to word, but do not change the value of var. |
${var:=word} |
If the variable var is empty or has been deleted (unset), return to Word and set the value of Var to word. |
${var:?message} |
If the variable var is empty or has been deleted (unset), then send message messages to the standard error output, which can be used to detect whether Var can be properly assigned. If this substitution appears in the shell script, the script will stop running. |
${var:+word} |
If the variable var is defined, it returns word but does not change the value of var. |
Take a look at the following example:
#!/bin/BashEcho${var:-"Variable is not set"}Echo "1-value of Var is ${var}"Echo${var:="Variable is not set"}Echo "2-value of Var is ${var}"unset varEcho${var:+"The is default value"}Echo "3-value of Var is $var"var="Prefix"Echo${var:+"The is default value"}Echo "4-value of Var is $var"Echo${var:?"Print This message"}Echo "5-value of Var is ${var}"
Operation Result:
Shell command substitution and variable substitution