#!/bin/bashDATE=`date`echo "Date is $DATE"USERS=`who | wc -l`echo "Logged in user are $USERS"UP=`date ; uptime`echo "Uptime is $UP"
運(yùn)行結(jié)果:
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
變量替換
變量替換可以根據(jù)變量的狀態(tài)(是否為空、是否定義等)來(lái)改變它的值
可以使用的變量替換形式:
形式
說(shuō)明
${var}
變量本來(lái)的值
${var:-word}
如果變量 var 為空或已被刪除(unset),那么返回 word,但不改變 var 的值。
${var:=word}
如果變量 var 為空或已被刪除(unset),那么返回 word,并將 var 的值設(shè)置為 word。
${var:?message}
如果變量 var 為空或已被刪除(unset),那么將消息 message 送到標(biāo)準(zhǔn)錯(cuò)誤輸出,可以用來(lái)檢測(cè)變量 var 是否可以被正常賦值。 若此替換出現(xiàn)在Shell腳本中,那么腳本將停止運(yùn)行。
${var:+word}
如果變量 var 被定義,那么返回 word,但不改變 var 的值。
請(qǐng)看下面的例子:
#!/bin/bash
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}"
運(yùn)行結(jié)果:
純文本復(fù)制
Variable is not set1 - Value of var isVariable is not set2 - Value of var is Variable is not set3 - Value of var isThis is default value4 - Value of var is PrefixPrefix5 - Value of var is Prefix