1、echo $?:任何命令进行时都将返回一个退出状态,输出上一个命令的退出状态,0表示退出成功。
2、测试文件状态:[ -w text ]测试文件是否可写,echo $?输出为0表示可写,否则不可写
[ -d text ]文件是不是目录,echo $?输出为1表示不是目录。0表示符合,1表示不符合。
[ -w text -a -d text ]文件是不是可写并且是不是路径,-a表示同and,-o表示or
- d 目录 - s文件长度大于0、非空
- f 正规文件 - w可写
- L 符号连接 - u文件有s u i d位设置
- r 可读 - x可执行
3、测试字符串:[string string_operator string]:如 [ $leeboy = "hello" ],[ -z $leeboy ]。
= 两个字符串相等。!=两个字符串不等。 -z空串。 -n非空串。
4、测试数值:[ number number_operator number ]:如[ $leeboy -eq 9 ]
-eq 数值相等。
-ne 数值不相等。
-gt 第一个数大于第二个数。
-lt 第一个数小于第二个数。
-le 第一个数小于等于第二个数。
-ge 第一个数大于等于第二个数。
5、if在脚本中的使用。
#!/bin/sh
#判断输入的是不是空
echo -e "Enter your name:\c"
read name
if [ "$name" = "" ] #此处必须用双引号,否则报错
then
echo "you did not enter your name!"
elif [ "$name" = "leeboy" ];then #如果then在一行写,中间要加“;”
echo "you are the one!"
else
echo "hello $name!"
fi
6、给脚本输入参数
#!/bin/sh
#判断输入的参数个数
if [ $# -lt 3 ] #$#是参数的个数
then
echo "Usage: `basename $0`: arg1 arg2 arg3"
exit 1
fi
echo "basename:$0" #$0表示shell脚本的名字
echo "arg1: $1" #shell的各个参数
echo "arg2: $2"
echo "arg3: $3"