您的位置:首页 > 运维架构 > Shell

bash条件测试及变量比较

2011-04-01 14:32 477 查看

bash条件测试及变量比较

一、 条件表达式

1. 基本的if语句if [ … ]then….Fi 2. 多个if语句if […]then…Elif […]Then…Fi 3. 嵌套if语句If […]Then… If[…] Then … FiElse…fi

二、 字符串和数字比较

NumberString
大于-gt/>
小于-lt/<
等于-eq==
大于等于-geSingle[] doesnot support
小于等于-leSingle[] doesnot support
不等于-ne!=

三、 关键点

1. if和elif后面有then2. else if是非法的3. 单个中括号[]里面的”<”和“ >”需要转义,且不支持”>=” 和“<=”4. “z” 测试字符串是否为NULL5. “n” 测试字符串是否不为NULL

四、 代码

#! /bin/bashecho "test you"a=12b=13 # number compare# -eq: equal# -ne: not equal# -gt: great# -ge: great and equal# -lt: little# -le: little and equalif [ "$a" -ne "$b" ]thenecho "$a is not equel to $b"fi if [ "$a" -eq "$b" ]then echo "$a is equal to $b"elseecho "$a is not equal to $b"fi if [ "$a" -eq "$b" ]thenecho "$a is equal to $b"elif [ "$a" -lt "$b" ]thenecho "$a is little to $b"elif [ "$a" -gt "$b" ]thenecho "$a is great to $b"elseecho "Default"fi#########Key Point#######################1."then" after "if" or "elif"#####################2."elif" is ok, not "else if"############ c=abcd=abde=#string compare if [ "$c" == "$d" ]thenecho "string $c is equal to $d"elif [ "$c" /> "$d" ]thenecho "string $c is great to $d"elif [ "$c" /< "$d" ]thenecho "string $c is little to $d"elif [ "$c" != "$d" ]thenecho "string $c is not equal to $d"fi if [ -z "$e" ]thenecho " $e is NULL"elseecho " $e is not NULL"fi if [ -n "$e" ]then echo "$e is not NULL"elseecho "$e is NULL"fi###########KEy point############################1.For string comparing, ">" "<"need escape symbol###########2."z": zero is used to test whether the string is NULL###########3."n": not zero is used to test whether the string is not NULL f=8if [ "$f" -gt 0 ]then echo "f is positive" if [ "$f" -gt 5 ] then echo "f is a big positive" else echo "f is a small positive" fielseecho "f is negative" if [ "$f" -gt -5 ] then echo "f is a big negative" else echo "f is a small negative" fifi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐