流程控制
if语句
1.单分支if条件语句
if [ 条件判断式 ];then
程序
fi
或
if [ 条件判断式 ]
then
程序
fi
#举例
#!/bin/bash
rate=$(df -h | grep "/dev/sda1" | awk '{print $5}' | cut -d "%" -f1)
#把根分区使用率作为变量值赋予变量rate
if [ $rate -ge 80 ]
then
echo "Warning! /dev/sda1 is full!!"
fi
2.双分支if条件语句
if [ 条件判断式 ]
then
条件成立,执行程序
else
条件不成立,执行另一个
fi
#案例
#!/bin/bash
ntpdate asia.pool.ntp.org &>/dev/null
#同步系统时间
date=$(date +%y%m%d)
size=$(du -sh /etc)
if [ -d /tmp/dbbak ]
then
echo "date : $date!" > /tmp/dbbak/dbinfo.txt
echo "date size : $size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /etc dbinfo.txt&>/dev/null
rm -rf /tmp/dbbak/dbinfo.txt
else
mkdir /tmp/dbbak
echo "date : $date" > /tmp/dbbak/dbinfo.txt
echo "date size : $size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /etc dbinfo.txt$>/dev/null
rm -rf /tmp/dbbak/dbinfo.txt
fi
3.多分支if条件语句
if [ 条件判断式 ]
then
条件成立,执行程序
elif [ 条件判断式 ]
then
条件不成立,执行另一个
........
else
条件成立,执行程序
fi
#案例
#!/bin/bash
read -p "Please input: " file
if [ -z "$file" ]
then
echo "Error"
exit 1
elif [ ! -e "$file" ]
then
echo "not a file"
exit 2
elif [ -f "$file" ]
then
echo "$file is a regulare file"
elif [ -d "$file" ]
then
echo "$file is a directory"
else
echo "$file is an other file"
fi
case语句
if可以判断多种,case可能判断一种
case $变量名 in
"值1")
如果变量值等于值1,则执行程序1
;;
"值2")
如果变量等于值2,则执行程序2
;;
*)
esac
#案例
#!/bin/bash
read -p "Please choose yes/no" -t 30 cho
case $cho in
"yes")
echo "yes"
;;
"no")
echo "no"
;;
*)
echo "error"
;;
esac
for语句
语法一
for 变量 in 值1 值2 值3 ....
do
程序
done
#案例1
#!/bin/bash
for time in morning noon afternoon evning
do
echo "this time is $time"
done
#案例2
#!/bin/bash
cd /lamp
ls *.tar.gz>ls.log
for i in $(cat ls.log)
do
tar -zxf $i &>/dev/null
done
rm -rf /lamp/ls.log
语法二
for ((初始值;循环控制条件;变量变换))
do
程序
done
#案例
#!/bin/bash
s=0
for((i=1;i<=100;i=i+1))
do
s=$(($s+$i))
done
echo $s
#案例
#!/bin/bash
read -p "name" -t 30 name
read -p "num" -t 30 num
read -p "pass" -t 30 pass
if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ]
then
y=$(echo $num | sed 's//[0-9]//g')
if [ -z "$y" ]
then
for((i=1;i<=$num;i=i+1))
do
useradd $name$i&>/dev/null
echo $pass | /usr/bin/passwd --stdin $name$i&>/dev/null
done
fi
fi
while循环与until循环
while
while [ 条件判断式 ]
do
程序
done
#案例
#!/bin/bash
i=1
s=0
while [ $i -le 100 ]
do
s=$(($s+$i))
i=$(($i+1))
done
echo $s
until
和while相反,条件成立终止
until [ 条件判断式 ]
do
程序
done