常用的語句
exit直接退出
break退出當前迴圈,不影響其他
continue跳出本層迴圈,進入下一次迴圈

[[email protected] mnt]# vim test.sh
#!/bin/bash
for NUM in {1..5}
do
        if
        [ "$NUM" -eq 3 ]
        then
                $1
        fi
        echo $NUM
done

echo hello,westos!


[[email protected] mnt]# sh test.sh
1
2
3
4
5
hello,westos!
[[email protected] mnt]# vim test.sh
[[email protected] mnt]# sh test.sh exit
1
2
[[email protected] mnt]# sh test.sh break
1
2
hello,westos!
[[email protected] mnt]# sh test.sh continue
1
2
4
5

hello,westos!


(1)for語句
[[email protected] mnt]# vim for.sh
#!bin/bash
for NUM in `seq 1 2 10` #使用seq可以設定步長
do
        echo $NUM
done
[[email protected] mnt]# sh for.sh
1
3
5
7
9
[[email protected] mnt]# vim for.sh
#!bin/bash
for NUM in {1..5} #相當於 `seq 1 5` , 也相當於((NUM=1;NUM<=5;NUM++))
do
        echo $NUM
done
[[email protected] mnt]# sh for.sh
1
2
3
4
5

實驗:顯示教室中可連通的網路
[[email protected] mnt]# vim check_host.sh
#!/bin/bash
for IP in `seq 0 50`
do
        ping -c1 -w1 172.25.254.$IP &> /dev/null && echo "172.25.254.$IP"
done

實驗:備份資料庫
[[email protected] mnt]# vim mysql_dump.sh
#!/bin/bash
DATABASE=`mysql -uroot -EN -e "show databases;"|grep -E "^\*|schema$" -v`
mkdir -p /mnt/mysql_dump
for DATABASE in $DATABASE
do
        mysqldump -uroot $DATABASE > /mnt/mysql_dump/${DATABASE}.sql
        [ "$?" -eq "0" ]&&{
                echo -e "\033[32m$DATABASE is backuped!\033[0m"
        }

done


[[email protected] mysql_backup]# sh  mysql_dump.sh
linux is backuped!
mysql is backuped!
test is backuped!

westos is backuped!


(2)while do語句
while true
do
    ***
done
實驗:當根分割槽使用量超過80%時,向root使用者傳送郵件警告
[[email protected] mnt]# vim root_check.sh
#!/bin/bash
COUNT=`df|awk -F " " '/\/$/{print $5}'|awk -F "%" '{print $1}'`
while true
do
        [ "$COUNT" -ge "80" ]&&{
                echo Your / is full!| mail -s warning root
        }
        sleep 1

done


[[email protected] ~]# mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/root": 3 messages 3 new
>N  1 root                  Mon Jun 18 05:07  18/601   "warning"
 N  2 root                  Mon Jun 18 05:07  18/601   "warning"
 N  3 root                  Mon Jun 18 05:07  18/601   "warning"
& q
You have mail in /var/spool/mail/root

[[email protected] ~]# > /var/spool/mail/root #清空郵件


實驗:當根分割槽使用量超過80%時,在當前shell環境中顯示
[[email protected] mnt]# vim root_check.sh
#!/bin/bash
COUNT=`df|awk -F " " '/\/$/{print $5}'|awk -F "%" '{print $1}'`
TTY=`ps $$|awk '/bash$/{print $2}'`
while true
do
        [ "$COUNT" -ge "80" ]&&{
                echo "Your / is full!"  >  /dev/$TTY
        }
        sleep 3
done

.