&&:用来执行条件成立后执行的命令
||:用来执行条件不成立后的执行命令
ping windows && echo yes || echo no windows能ping通 输出yes 不能ping通输出no
ls && echo yes || echo no ls执行成功 输出yes 执行不成功输出no
整数测试
注意 符号 两边要有空格
test 1 = 1 && echo yes || echo no 1 == 1
test 1 != 1 && echo yes || echo no 1 != 1
test 1 -eq 1 && echo yes || echo no 1 == 1
test 1 -ne 1 && echo yes || echo no 1 != 1
test 1 -gt 2 && echo yes || echo no 1 > 2
test 1 -lt 2 && echo yes || echo no 1 < 2
test 1 -ge 2 && echo yes || echo no 1 >= 2
test 1 -le 2 && echo yes || echo no 1 <= 2
a=1
b=2
test $a = $b && echo yes || echo no
test $a != $b && echo yes || echo no
test $a && echo yes || echo no a存在 输出 yes 不存在输出 no
test $a -a $a = 1 && echo yes || echo no yes
test $a -a $a = 2 && echo yes || echo no no
test $a -o $a = 2 && echo yes || echo no yes
test命令通常做判断, test 命令和 [ ] 等同
#前后必须有空格
[1 = 1] && echo yes || echo no 错误
[ 1 = 1 ] && echo yes || echo no 正确
字符串测试
test "abc" == "bcd" && echo yes || echo no 判断字符串相等 注意 == 两边要有空格
test "abc" != "bcd" && echo yes || echo no 判断字符串不相同
判断字符串不是null
test $abc && echo yes || echo no abc 存在 输出 yes 不存在输出 no
判断字符串是null
test -z $abc && echo yes || echo no abc不存在 输出yes 存在输出 no
[ $abc ] && echo yes || echo no 不是空 yes 是空 no
if(name !=null ){
}
文件测试
-d 判断是否是文件夹
-f 判断是否是文件
-L 判断是否是超链接 快捷方式
-e 判断是否存在
-r 判断是否有读权限
-w 判断是否有写权限
-x 判断是否是执行权
test -d 1.txt && echo yes || echo no
[ -d 1.txt ] && echo yes || echo no
[ -f 1.txt ] && echo yes || echo no
[ -e 1.txt ] && echo yes || echo no
[ -L /bin ] && echo yes || echo no
[ -r 1.txt -a -w 1.txt ] && echo yes || echo no
[ -x 1.txt ] && echo yes || echo no
if语句判断
单条件判断
if [ 条件 ]
then
执行
fi
互斥条件判断
if [ 条件 ]
then
程序
else
程序
fi
#!/bin/bash
read -p '请输入您的年龄:' AGE
if [ $AGE -ge 18 ]
then
echo "你成年了可以看片了"
else
echo "你还未成年 滚蛋"
fi
#判断传入的参数 $1是否存在 存在打印值 不存在 则输出不存在
#!/bin/bash
name=$1
if [ $name ]
then
echo "$name"
else
echo "name不存在"
fi
多条件判断
if [ 条件1 ]
then
执行
elif [ 条件2 ]
then
执行
...
else
执行
fi
#!/bin/bash
if [ $1 -ge 90 -a $1 -le 100 ]
then
echo "优秀"
elif [ $1 -ge 80 -a $1 -lt 90 ]
then
echo "良好"
elif [ $1 -ge 60 -a $1 -lt 80 ]
then
echo "及格"
elif [ $1 -ge 0 -a $1 -lt 60 ]
then
echo "潜力非常大"
else
echo "分数有误"
fi