-z string 如果 string 长度为零,则为真 [ -z $myvar ]
-n string 如果 string 长度非零,则为真 [ -n $myvar ]
string1 = string2 如果 string1 与 string2 相同,则为真 [ $myvar = one two three ]
string1 != string2 如果 string1 与 string2 不同,则为真 [ $myvar != one two three ]
算术比较运算符
num1 -eq num2 等于 [ 3 -eq $mynum ]
num1 -ne num2 不等于 [ 3 -ne $mynum ]
num1 -lt num2 小于 [ 3 -lt $mynum ]
num1 -le num2 小于或等于 [ 3 -le $mynum ]
num1 -gt num2 大于 [ 3 -gt $mynum ]
num1 -ge num2 大于或等于 [ 3 -ge $mynum ]
脚本示例:
#!/bin/bash
# This script prints a message about your weight if you give it your
# weight in kilos and hight in centimeters.
if [ ! $# == 2 ]; then
echo "Usage: $0 weight_in_kilos length_in_centimeters"
exit
fi
weight="$1"
height="$2"
idealweight=$[$height - 110]
if [ $weight -le $idealweight ] ; then
echo "You should eat a bit more fat."
else
echo "You should eat a bit more fruit."
fi
# weight.sh 70 150
You should eat a bit more fruit.
# weight.sh 70 150 33
Usage: ./weight.sh weight_in_kilos length_in_centimeters
位置参数 $1, $2,..., $N,$#代表了命令行的参数数量, $0代表了脚本的名字,
第一个参数代表$1,第二个参数代表$2,以此类推,参数数量的总数存在$#中,上面的例子显示了怎么改变脚本,如果参数少于或者多余2个来打印出一条消息。
执行,并查看情况。
# bash -x tijian.sh 60 170
+ weight=60
+ height=170
+ idealweight=60
+ '[' 60 -le 60 ']'
+ echo 'You should eat a bit more fat.'
You should eat a bit more fat.
其中-x用来检查脚本的执行情况。
|