Shell command substitution and variable substitution

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.