test语句(变量测试,测试文件,字符串,整数)
测试字符串
test str1==str2 是否相等
test str1!=str2 是否不相等
test str1 测试字符串是否不空
test -n str1 测试字符串是否为空
测试整数
test int1 -eq int2 ==
test int1 -ge int2 >=
test int1 -gt int2 >
test int1 -le int2 <=
test int1 -lt int2 <
test int1 -ne int2 !=
测试文件
test -d file 测试是否为目录
test -f file 测试是否为文件
test -x file 测试文件是否可执行
test -r file 测试文件是否可读
test -w file 测试文件是否可写
test -e file 测试文件是否存在
test -s file 测试文件大小是否为空
以上test可以用[]代替,如:[ int1 -lt int2 ] [ -x file ]
if语句,if else语句,if elif else 语句
if 条件 ; then
命令
elif 条件 ; then
命令
else
命令
fi
if和条件之间要有空格,条件后面跟的分号要有空格
举例:
#!/bin/bash
read filename
if [ -f $filename ] ; then
echo "$filename is file"
elif [ -d $filename ] ; then
echo "$filename is dir"
elif [ -c $filename -o -b $filename ] ; then
echo "$filename is device file"
else echo "$filename is unknow file"
fi
结果:
case语句
语法:
case 变量 in
字符串1) 命令列表1
;;
字符串2) 命令列表2
;;
*) 命令列表 #匹配所有
;;
esac
for语句
语法:
for 变量 in 名字表
do
命令
done
举例:
#!/bin/bash
for DAY in Sunday Monday Tuesday Wednesday Thursday Friday Saturday
do
echo "The Day is:$DAY"
done
结果:
while语句
语法:
while 条件(条件为真就进行do)
do
命令
done
举例:
#!/bin/bash
num=1
while [ $num -le 10 ]
do
echo "$num*$num =" `expr $num \* $num`
num=`expr $num + 1`
done
结果:
发现一个问题,shell里面运算不能使用$num+1,只能使用expr