if
- 变量赋值,等号之间不能有空格
- 条件判断是中括号要留有空格
#语法结构
#如果if条件判断中有多条命令,则根据最后一条命令的执行结果进行评估
if command;then
command
elif command;then
command
else
command
fi
#!/bin/bash
x=5
if [ $x = 5 ];then
echo "x equals 5"
else
echo "x not equals 5"
fi
退出状态
每个命令执行完成后,会向操作系统发送一个值,表示退出状态,可以使用以下方法,查看该值
#0表示执行成功,其他值表示失败
echo $?
test
语法结构
(一)
test expression
(二)
[ expression ]
文件判断
-d file 文件存在,并且是一个目录文件
-e file file文件存在
-f file file问价存在,并是一个普通文件
-r file 问价存在,并且可读
-w file 文件存在,并且可写
-x file 文件存在,并且可执行
#!/bin/sh
file="/usr/study/test/test.t"
if [ -e $file ];then
if [ -f $file ] ;then
echo "$file is a regular file"
fi
if [ -d $file ];then
echo "$file if a directory"
fi
if [ -r $file ];then
echo "$file is a readable"
fi
if [ -w $file ];then
echo "$file is a writeable"
fi
if [ -x $file ];then
echo "$file is a executable"
fi
else
echo "$file does not exit"
exit 1
fi
exit
#exit命令接受单独的可选参数,来作为脚本的退出状态
字符串表达式
">"和"<"在使用是必须使用引号引起来,或者使用反斜杠进行转义
"="和"=="在判断字符串相等是作用相同
-n string 表示字符串长度大于0
-z string 表示字符串长度等于0
#!/bin/bash
result=xul
if [ -z $result ];then
echo "there is no answer"
exit 1
fi
if [ "$result" = "xul" ];then
echo "result is xul"
fi
if [ "$result" != "test" ];then
echo "result is not test"
fi
if [ "$result" \> "yyy" ];then
echo "result > yyy"
fi
if [ "$result" \< "yyy" ];then
echo "result < yyy"
fi
整数表达式
-eq 连个整数相等
-ne 两个整数不相等
-le 小于等于
-lt 小于
-ge 大于等于
-gt 大于
#!/bin/bash
i=4
if [ -z "$i" ];then
echo "i is empty"
exit 1
fi
if [ $i -eq 0 ];then
echo "i is 0"
else
if [ $i -le 0 ];then
echo "i <= 0"
fi
if [ $i -ge 0 ];then
echo "i >= 0"
fi
if [ $i -ne 0 ];then
echo "i != 0"
fi
if [ $((i%2)) -eq 0 ];then
echo "i is even"
fi
fi
exit
增强版test
[[ espression ]]
1.增加了对正则表达式的支持
2.==操作符支持模式匹配
(())
算数测试,使用变量是不需要扩展操作,该表达式可以根据变量名直接查找变量
#!/bin/bash
i=5
if [[ "$i" =~ ^-?[0-9]+$ ]];then
if [ $i -eq 0 ];then
echo "$i is 0"
else
if [ $i -lt 0 ];then
echo "$i < 0"
else
echo "$i > o"
fi
if [ $((i%2)) == 0 ];then
echo "$i is even"
else
echo "$i is not even"
fi
fi
else
echo "$i is not a integer"
fi
逻辑表达式
&& || !
#!/bin/bash
i=50
max=100
min=1
if [[ "$i" =~ ^-?[0-9]+$ ]];then
if [[ i -ge min && i -le max ]];then
echo "$i is within $min to $max"
else
echo "$i is out of range"
fi
else
echo "$i is not a integer"
fi
控制运算符
command1&&command2
//只有command1执行成功后才执行command2
command1||command2
//只有command1执行失败后才执行command2
mkdir test && cd test