Sunday, July 12, 2015


1. Command Substitution
Syntax:
 `command`  

Ex:
 #!/bin/sh  
   
 DATE=`date`  
 echo "Date is $DATE"  
   
 USERS=`who | wc -l`  
 echo "Logged in user are $USERS"  
   
 UP=`date ; uptime`  
 echo "Uptime is $UP"  

 $./test.sh  
 Date is Thu Jul 2 03:59:57 MST 2009  
 Logged in user are 1  
 Uptime is Thu Jul 2 03:59:57 MST 2009  
 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15  

2. Variable Substitution
Form Description
${var} Substitue the value of var.
${var:-word} If var is null or unset, word is substituted for var. The value ofvar does not change.
${var:=word} If var is null or unset, var is set to the value of word.
${var:?message} If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
${var:+word} If var is set, word is substituted for var. The value of var does not change.

Ex:
 #!/bin/sh  
   
 echo ${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 var  
 echo ${var:+"This is default value"}  
 echo "3 - Value of var is $var"  
   
 var="Prefix"  
 echo ${var:+"This is default value"}  
 echo "4 - Value of var is $var"  
   
 echo ${var:?"Print this message"}  
 echo "5 - Value of var is ${var}"  

 $./test.sh  
 Variable is not set  
 1 - Value of var is  
 Variable is not set  
 2 - Value of var is Variable is not set  
   
 3 - Value of var is  
 This is default value  
 4 - Value of var is Prefix  
 Prefix  
 5 - Value of var is Prefix  

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Lập trình hệ thống nhúng Linux . Powered by Luong Duy Ninh -