Shell編程之流程控制

判斷文件類型

-d:文件是否存在,若存在且爲目錄
-e:文件是否存在
-f:文件是否存在且是否只是普通文件
例子:[ -e /home/lcl/lab3.txt ]是判斷/home/lcl/lab3.txt文件是否存在,注意中括號前後必須帶空格

判斷文件權限

-r:文件是否存在且有讀權限。
-w:文件是否存在且有寫權限。
-x:文件是否存在且有執行權限。

文件比較

文件1 -nt 文件2 :文件1是否比文件2新。
文件1 -ot 文件2 :文件1是否比文件2舊。
文件1 -ef 文件2 :文件1是否和文件2的inode一致,即是否兩個文件的是硬鏈接的。


第一步:創建硬鏈接:ln lab3.txt labhl.txt
第二步:
這裏寫圖片描述

數值比較

比較1111和123:[ 1111 -gt 123 ]
加了-gt的數值比較符號,兩邊就會按數值來比較,而不是比較字符串。
等於:eq,不等於:ne,大於等於:ge
gt:greater than ,lt:less than ,le:less equal (<=)

字符串判斷

-z:字符串爲空返回真
-n:字符串不爲爲空返回真
字符串1 == 字符串2:判斷字符串是否相等
字符串1 != 字符串2:判斷字符串是否不等
例子:a=1,b=22

[  $a != $b ] && echo "yes" || echo "no"

“==” 和 ”!=” 兩邊必須要有空格

多重條件判斷

判斷1 -a 判斷2:判斷1和2同時爲真返回真
判斷1 -o 判斷2:判斷1和2有一個爲真返回真
! 判斷:取非(注意空格)

判斷httpd服務是否開啓

#!/bin/bash

test=$(ps aux | grep httpd | grep -v "root")
if [ -n "$test" ]
        then
                echo "httpd is ok"
        else
                echo "httpd is stop"
                /etc/rc.d/init.d/httpd start
                echo "$(date) httpd is start!"
fi

多分支 if 判斷

輸入是文件類型是什麼

#!/bin/bash

read  -t 30 -p "input filename:" file
if [ -z "$file" ]
        then
                echo "input can not be null"
                exit 1
elif [ ! -e "$file" ]
        then
                echo "your input is not a file"
                exit 2
elif [ -d "$file" ]
        then
                echo "your input is a directory"
                exit 3
elif [ -f "$file" ]
        then
                echo "your input is a file"
                exit 4
else
                echo "your input is an other file"
                exit 5
fi

多分支case語句例子

echo "input 1 -> hh will kiss you "
echo "input 2 -> hh will hug you"
echo "input 3 -> hh will love you"

read -t 30 -p "input choose:" cho
case "$cho" in
        "1")
                echo "hh kiss me!"
                ;;
        "2")
                echo "hh hug me!"
                ;;
        "3")
                echo "hh love me!"
                ;;
        *)
                echo "input error"
                ;;
esac

for循環

將當前目錄”*.tar”文件解壓縮

#!/bin/bash

ls *.tar > for.log
for i in $(cat ./for.sh)
        do
                #輸出到/dev/null即放進回收站
                tar -zxvf $i &> /dev/null
        done
rm -rf for.log

while循環

例:從1加到100

i=1
s=0
while [ $i -le 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done
echo $s    

Until循環

#!/bin/bash

i=0
s=0

until [ $i -gt 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done
echo "sum is $s"

until循環是條件滿足時終止循環

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章