shell学习之if句练习

夜晚编程,安静!

语法

关于fi 网上的同志萌都说是 if 反过来,认为是end if。

我觉得可以通过finally来记,因为条件句执行完毕不论如何都会执行

和python或者java里的finally很像。

if [ command ];then
    符合条件1执行的语句1
elif [ command ];then
    符合条件2执行的语句2
else
    符合条件3执行的语句3
fi
     执行最后一句

数值判断

-eq表示equal等于

-neq表示not equal不等于

-gt即greater than

-lt表示less than

简单测试数值比较

# !/bin/bash
# author
NUM1=1
NUM2=2
if (($NUM1 > $NUM2));then
        echo "this is flase"
else
        echo "this is True!"
fi
        echo 23333

image-20200428010554792

多试试加参数得方式

#!/bin/bash
#author h3zh1
Score=85
if [[ $Score -eq 85 ]];then
        echo "\$Score = 85!"
fi
if [[ $Score -gt 60 ]];then
        echo "greate than 60"
elif [[ $Score -lt 100 ]];then
        echo "less than 100"
else
        echo "else  else"
fi

image-20200428010623743

if判断目录存不存在

-d用于判断目录存不存在

#!/bin/bash                                 
#judge if dir exits                             
DIR=learn/                                  
if [ ! -d $DIR ];then                       
        mkdir -p $DIR                       
        echo "not exit && mkdir success!"               
else                                        
        echo "This dir $DIR exits , die…" 
fi                                          

image-20200428010515453

判断文件存不存在

-f 判断文件是否存在

#!/bin/bash
#author h3zh1

FILES=learn/flag.txt                                   
if [ ! -f $FILES ];then                                
        echo "not exit $FILES"                         
        echo "i am write flag{h3zh1} to file" >> $FILES
else                                                   
        echo -e "----------------------"               
        cat $FILES                                     
fi                                                

运行两次,第一次创建文件,并写点东西

第二次文件已经存在就不需要写了

image-20200428010743205

吐个槽最近一直写出来.swp文件,对这个文件泄露估计以后会
很深刻了。

详细的参数可以参考

https://www.cnblogs.com/kaishirenshi/p/9729800.html