Shell编程之流程控制
判断文件类型 -d:文件是否存在,若存在且为目录 判断文件权限 -r:文件是否存在且有读权限。 文件比较 文件1 -nt 文件2 :文件1是否比文件2新。 例 数值比较 比较1111和123:[ 1111 -gt 123 ] 字符串判断 -z:字符串为空返回真 [ $a != $b ] && echo "yes" || echo "no"
“==” 和 ”!=” 两边必须要有空格 多重条件判断 判断1 -a 判断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循环是条件满足时终止循环 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |