微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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循环是条件满足时终止循环

原文地址:https://www.jb51.cc/bash/390552.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐