<div>#!/bin/bash</div><div>DATE=`date`</div><div>echo "Date is $DATE"</div><div>USERS=`who | wc -l`</div><div>echo "Logged in user are $USERS"</div><div>UP=`date ; uptime`</div><div>echo "Uptime is $UP"</div>
复制代码
运行结果:
<div>Date is Thu Jul 2 03:59:57 MST 2009</div><div>Logged in user are 1</div><div>Uptime is Thu Jul 2 03:59:57 MST 2009</div><div>03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15</div>
复制代码
变量替换
变量替换可以根据变量的状态(是否为空、是否定义等)来改变它的值
可以使用的变量替换形式:
形式 说明
${var} 变量本来的值
${var:-word} 如果变量 var 为空或已被删除(unset),那么返回 word,但不改变 var 的值。
${var:=word} 如果变量 var 为空或已被删除(unset),那么返回 word,并将 var 的值设置为 word。
${var:?message} 如果变量 var 为空或已被删除(unset),那么将消息 message 送到标准错误输出,可以用来检测变量 var 是否可以被正常赋值。
若此替换出现在Shell脚本中,那么脚本将停止运行。
${var:+word} 如果变量 var 被定义,那么返回 word,但不改变 var 的值。
请看下面的例子:
<div>#!/bin/bash</div><div>echo ${var:-"Variable is not set"}</div><div>echo "1 - Value of var is ${var}"</div><div>echo ${var:="Variable is not set"}</div><div>echo "2 - Value of var is ${var}"</div><div>unset var</div><div>echo ${var:+"This is default value"}</div><div>echo "3 - Value of var is $var"</div><div>var="Prefix"</div><div>echo ${var:+"This is default value"}</div><div>echo "4 - Value of var is $var"</div><div>echo ${var:?"Print this message"}</div><div>echo "5 - Value of var is ${var}"</div>
复制代码
运行结果:
<div>Variable is not set</div><div>1 - Value of var is</div><div>Variable is not set</div><div>2 - Value of var is Variable is not set</div><div>3 - Value of var is</div><div>This is default value</div><div>4 - Value of var is Prefix</div><div>Prefix</div><div>5 - Value of var is Prefix</div>