shell脚本中的逻辑判断,文件目录属性判断, if特殊用法,case判断

shell脚本中的逻辑判断:

逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 -gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=) 注意到处都是空格 then=满足条件 else=不满足条件

第一种格式:if 条件 ; then 语句 ; fi

第二种格式:if 条件 ;then 语句 ;else 语句 ;fi a=1那么久不满足条件,就是else。

a=1 那么 a 就不>3 所以就不满足条件,就是else

第三种格式:if …; then … ;elif …; then …; else …; fi

文件目录属性判断:

【 if file 】 判断是否是普通文件,切存在

【-d file 】判断是否是目录,且存在

【 -e file 】判断文件或目录是否存在

【 -r file 】判断文件是否可读 可写 可执行 = 类似

判断的不同写法:【 -f $f 】|| touch $f

if [ ! -f $f] ! = 非,取反

then

touch $f

fi

if 特殊用法:

if [ -z "$a" ] 这个表示当变量a的值为空时会怎么样

if [ -n "$a" ] 表示当变量a的值不为空

if grep -q '123' 1.txt; then 表示如果1.txt中含有'123'的行时会怎么样

if [ ! -e file ]; then 表示文件不存在时会怎么样

if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…

[ ] 中不能使用<,>,==,!=,>=,<=这样的符号

if [ -z “$a” ] 这个表示当变量a的值为空时会怎么样

#!/bin/bash
n='wc -l /tmp/lalala'
if [ $n -lt 100 ]
then
       echo "line num less than 100"
fi
# 如果/tmp/lalala文件为空,或者被删除的话,脚本就会运行出错,出现bug

应该加上一个判断条件
#!/bin/bash
n='wc -l /tmp/lalala'
if [ $n -z "$n" ]
# [ $n -z "$n" ]  = [ ! $n -n "$n" ],-z 和 -n 是一对相反的条件
then
       echo "error"
       exit
elif [ $n -lt 100 ]
then
        echo "line num less than 100"
fi

或者
#!/bin/bash
if [ ! -f /tmp/lalala ]
then
       echo "/tmp/lalala is not exist"
       exit
fi

n='wc -l /tmp/lalala'
if [ $n -lt 100 ]
then
        echo "line num less than 100"
fi

case判断:

case 变量名 in
    value1)
      commond1
      ;;
    value2)
      commod2
      ;;
    value3)
      commod3
      ;;
esac

脚本案例:

在网卡系统服务脚本中,如,/etc/init.d/iptables中就用到了case

在case中,可以在条件中使用“|”,表示或的意思

输入一个同学的分数,判断成绩是否及格,优秀。


#!/bin/bash
read -p "Please input a number: " n
# read -p 是读取用户的输入数据,定义到变量里面
if [ -z "$n" ]
then
    echo "Please input a number."
    exit 1
#“exit 1”表示非正常运行导致退出程序
#退出之后,echo $?会返回1值,表示程序退出是因为出错了,和查看上一条命令执行有无错误的时候是一样的。
fi

n1=`echo $n|sed 's/[0-9]//g'`
#判断用户输入的字符是否为纯数字
#如果是数字,则将其替换为空,赋值给$n1
if [ -n "$n1" ]
then
echo "Please input a number."
exit 1
#判断$n1不为空时(即$n不是纯数字)再次提示用户输入数字并退出
fi

#如果用户输入的是纯数字则执行以下命令:
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
    tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
    tag=2
elif [ $n -ge 80 ]  && [ $n -lt 90 ]
then
    tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
    tag=4
else
    tag=0
fi
#tag的作用是为判断条件设定标签,方便后面引用
case $tag in
    1)
        echo "not ok"
        ;;
    2)
        echo "ok"
        ;;
    3)
        echo "ook"
        ;;
    4)
        echo "oook"
        ;;
    *)
        echo "The number range is 0-100."
        ;;
esac

猜你喜欢

转载自my.oschina.net/u/3769333/blog/1821525