shell--条件判断与测试

来源:互联网 发布:js代码整理 编辑:程序博客网 时间:2024/06/05 09:11
条件测试使用test和 []
test 表达式
[ 表达式 ]
 $? 是一个系统变量,用来获取shell命令的执行状态,若执行成功,则返回值为0否则就返回1
注意:在测试运算符=,!=,-z等符号的左右两边,一定要有一个空格

字符串测试
test
[ ]
string:判断指定的字符串是否为空串
-n string :判断是否为非空串
-z string :判断是否为空串

整数测试
test number op number
[ number op number ]
ps:字符串运算符和整数运算符不可混用
-eq,-ne,-gt,lt,ge,le

文件测试
test op(操作符) file
-a file 存在
-b file 存在且为块文件
-c file 存在且为字符文件
-d file 存在且为目录
-s file 文件长度大于0且文件为非空
-f file 存在且为常规文件
-w file 存在且可写
-L file 存在且为符号链接
-u file 是否设置了suid位
-r file 存在且可读
-x file 存在且可执行
chomd u+s hello.sh 为hello.sh 设置了setuid权限


逻辑运算符
!expression
expression -a expression &&
expression -o expression ||


条件判断
if expression   or   if expression;then
then                 ...
....                 ...
....                 fi
fi
在shell中有一个空命令,其表示为:
if :
then
  echo "always true"
fi
使用if else 语句
if expression
then
..
else
fi
使用if elif语句
if expression
then
  ...
elif expression
then
  ...
else
  ...
fi
使用exit 语句退出程序exit 0~255
多条件判断语句case
case "变量" in
value1)
  。。。
  。。。;;
value2)
  ...
  ...;;
*)
  ...
  ...;;
esac

;;作为结束符号,会跳过当前case语句后面的所有的case语句,执行esac字句后面所有的其他语句

算术运算符,+  -  *(需要转义字符\*)   / %  **

1、使用expr是外部程序
expr 是shell的一个命令,可以计算某个表达式的值
`expr expression`使用的是反引号,expr不能计算幂运算

2、使用$(())
这种形式进行算术运算的写法比较自由,不需要对运算符和括号进行转义处理,

3、使用$[]来执行,同2