1. 程式人生 > >Linux——for、while、if、case四大shell語句簡單舉例

Linux——for、while、if、case四大shell語句簡單舉例

一、三個指令碼退出語句

Exit 結束指令碼,整體退出
Break 允許跳出所有迴圈(終止執行後面的所有迴圈)
Continue 提前結束當前迴圈,進入下一個迴圈

為了更清楚的瞭解這幾個的區別進行以下實驗:
root@desktop26 mnt]# cat test1.sh 
#######################################
# Author:       yifan                 #
# Version:                            #
# Mail:                               #
# Date:         2018
-51-06/25/18 # # Description: # # # ####################################### #!/bin/bash for NUM in {1..5} //從1到4迴圈 do if [ "$NUM " -eq 3 ] //判斷NUM是否等於3 then $1 //這裡輸入指令碼後輸入的三個測試值 fi echo $NUM done echo hello [root@desktop
26 mnt]# sh test1.sh exit //當NUM=3後直接全部退出指令碼 1 2 [root@desktop26 mnt]# sh test1.sh continue //當NUM=3後,不執行後面的“echo NUM”,直接進入下次迴圈 1 2 4 5 hello [root@desktop26 mnt]# sh test1.sh break //結束for的所有迴圈,進入下一步命令“echo hello” 1 2 hello

這裡寫圖片描述
這裡寫圖片描述

二、for語句

for做的是批處理
格式:
for (變數)in (取值)
do
done

2.1 、{1..5}和`seq 1 5`的辨析

   {1..5}是1到5迴圈,`seq 1 5 `也是1到5迴圈,但不同的時seq可以設定步長 ,比如` seq 1 2 6`指的是從1到6每次增加兩個數,而且seq 比”{}”更高階,其裡面可以加變數名。但是“{}”內不可識別變數。

為了更清楚的比較,我們來看以下實驗:
[root@desktop26 mnt]# cat test2.sh 
#!/bin/bash
for NUM in {1..5}     //{1..5}
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 
1
2
3
4
5
[root@desktop26 mnt]# vim test2.sh
[root@desktop26 mnt]# cat test2.sh 
#!/bin/bash
for NUM in `seq 1 5`
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 
1
2
3
4
5
[root@desktop26 mnt]# vim test2.sh
[root@desktop26 mnt]# cat test2.sh 
#!/bin/bash
for NUM in `seq 1 2 5`  //從1到5,步長為2,即1.3.5.
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 
1
3
5

這裡寫圖片描述
這裡寫圖片描述

實驗一:判斷機房IP是否ping通

#!/bin/bash
for HOSTNUMBER in `seq 1 50`
do
   ping -c1 -w1 172.25.254.$HOSTNUMBER &>/dev/null && {    
          echo -e "\033[32m 172.25.254.$HOSTNUMBER is up;\033[0m"     
} || {
          echo -e "\033[31m 172.25.254.$HOSTNUMBER is down;\033[0m"
}        //ping通顯示ip up ,否則顯示 ip down,/033加的是輸出的顏色值,此時需加-e識別。
done

[root@desktop mnt]# sh  check_host.sh 
 172.25.254.1 is up;
 172.25.254.2 is up;
 172.25.254.3 is up;
 172.25.254.4 is up;
 172.25.254.5 is up;
 172.25.254.6 is up;
 172.25.254.7 is up;
 172.25.254.8 is up;
 172.25.254.9 is up;
 172.25.254.10 is up;
 172.25.254.11 is up;
 172.25.254.12 is down;
 172.25.254.13 is up;
 172.25.254.14 is up;
 172.25.254.15 is down;
 172.25.254.16 is up;
 172.25.254.17 is up;
 172.25.254.18 is down;
 172.25.254.19 is up;
 172.25.254.20 is up;
 172.25.254.21 is up;
 172.25.254.22 is down;
 172.25.254.23 is up;
 172.25.254.24 is down;
 172.25.254.25 is up;
 172.25.254.26 is up;
 172.25.254.27 is up;
 172.25.254.28 is up;
 172.25.254.29 is up;
 172.25.254.30 is up;
 172.25.254.31 is down;
 172.25.254.32 is up;
 172.25.254.33 is up;
 172.25.254.34 is down;
 172.25.254.35 is up;
 172.25.254.36 is up;
 172.25.254.37 is up;
 172.25.254.38 is up;
 172.25.254.39 is up;
 172.25.254.40 is up;
 172.25.254.41 is up;
 172.25.254.42 is up;
 172.25.254.43 is up;
 172.25.254.44 is up;
 172.25.254.45 is up;
 172.25.254.46 is up;
 172.25.254.47 is up;
 172.25.254.48 is up;
 172.25.254.49 is up;
 172.25.254.50 is down;

這裡寫圖片描述
這裡寫圖片描述

實驗二:建立一個數據庫,利用指令碼對所有資料庫進行備份操作,每個資料庫備份到一個檔案中,並以.sql結尾,最後儲存在到/mnt/mysql_dump目錄下。

1.建立資料庫:

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.35-MariaDB MariaDB Server

Copyright (c) 2000, 2013, Oracle, Monty Program Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database linux;
Query OK, 1 row affected (0.10 sec)

MariaDB [(none)]> use linux
Database changed
MariaDB [linux]> create table linux_user(
    -> username varchar(50) not null,
    -> password varchar(50) not null);
Query OK, 0 rows affected (0.14 sec)

MariaDB [linux]> insert into linux_user values("user1","123");
Query OK, 1 row affected (0.11 sec)

MariaDB [linux]> insert into linux_user values("user2","234");
Query OK, 1 row affected (0.10 sec)

MariaDB [linux]> select * from linux_user;
+----------+----------+
| username | password |
+----------+----------+
| user1    | 123      |
| user2    | 234      |
+----------+----------+2 rows in set (0.00 sec)

MariaDB [linux]> quit
Bye

這裡寫圖片描述

2.編寫指令碼如下:

這裡寫圖片描述

三、while語句

格式(當條件為真時執行do):
while true
do
done

實驗一:編寫指令碼,實時監控根分割槽的使用情況,超過80%就給超級使用者傳送一封警告郵件

指令碼內容:
[root@localhost mnt]# vim warning.sh
#!/bin/bash
NUM=`df -h | awk '/\/$/{print $5}' | awk -F "%" '{print $1}'`   //篩選出/使用情況百分比數字
while true
do
        [ "$NUM" -ge 80 ] && {
                echo "Your / will full !" | mail -s warning root
        }
        sleep 1    //每隔1秒執行一次
done                                                   

這裡寫圖片描述

root@node1 mnt]# df  //檢視根分割槽使用情況
Filesystem           Used Available Use% Mounted on
/dev/vda1           10473900 9488536    985364  29% /
devtmpfs              469344       0    469344   0% /dev
tmpfs                 484932      84    484848   1% /dev/shm
tmpfs                 484932   12784    472148   3% /run
tmpfs                 484932       0    484932   0% /sys/fs/cgroup
/dev/mapper/vg0-vo    483670    2368    451811   1% /home
[root@node1 mnt]# sh test.sh &  //執行指令碼,並打入後臺
[3] 4151
[root@node1 mnt]# mail  //檢視沒有郵件
No mail for root
[root@node1 mnt]# dd if=/dev/zero of=/bigfile bs=1M count=6000//擷取6000M的記憶體使根分割槽使用率變成80%以上
[root@node1 mnt]# df
Filesystem             Used Available Use% Mounted on
/dev/vda1           10473900 9488536    985364  91% /
devtmpfs              469344       0    469344   0% /dev
tmpfs                 484932      84    484848   1% /dev/shm
tmpfs                 484932   12784    472148   3% /run
tmpfs                 484932       0    484932   0% /sys/fs/cgroup
/dev/mapper/vg0-vo    483670    2368    451811   1% /home
[root@node1 mnt]# sh test.sh &  //執行指令碼並打入後臺
[3] 4151
[root@node1 mnt]# mail  //可以查到郵件
Heirloom Mail version 12.5 7/5/10.  Type ? for help."/var/spool/mail/root": 23 messages 23 new
>N  1 root                  Thu Jun 27 03:11  18/590   "warning"
 N  2 root                  Thu Jun 27 03:11  18/590   "warning"
 N  3 root                  Thu Jun 27 03:11  18/590   "warning"
 N  4 root                  Thu Jun 27 03:11  18/590   "warning"

四、If語句

格式
if
then
elif
then
、、、、、
else
fi

實驗一:編寫指令碼,判斷檔案型別

指令碼內容:
#!/bin/bash
if
[ "$#" -ne "1" ]
then
    echo " please input a file  after script!!"

elif
[ ! -e "$1" ]
then
    echo " $1 is not exist! "
elif
[ -b "$1" ]
then

    echo " $1 is a block special!"
elif
[ -f "$1" ]
then

    echo " $1 is a regular file!"
elif
[ -L "$1" ]
then

    echo " $1 is a symbolic link! "
elif
[ -d "$1" ]
then

    echo " $1 is a directory! "
else
   echo unknow $1
fi

這裡寫圖片描述

測試:
[root@localhost mnt]# sh check_file.sh mysql_dump
 mysql_dump is a directory! 
[root@localhost mnt]# sh check_file.sh check_file.sh 
 check_file.sh is a regular file!
[root@localhost mnt]# sh check_file.sh
 please input a file  after script!!

實驗二:寫一個建立使用者的指令碼,後更使用者檔案和密碼檔案且符合下列要求

1.檔案數量不對報錯;

2.檔案不存在報錯;

3.兩個檔案存在差異報錯;4.使用者存在時顯示使用者存在。但是不改變此使用者的密碼。

5.使用者不存在時,建立使用者並設定相應的密碼

指令碼內容:
[root@localhost mnt]# cat user_create.sh
#!/bin/bash
##############################Check Rule########################################
if
[ "$#" -ne "2" ]//判斷輸入檔案是否為兩個
then

    echo  -e "\033[31m please give me userfile and passfile after script !!\033[0m"   
    exit 1

elif
[ ! -e "$1" ]  //判斷輸入檔案1是否為存在
then
    echo -e  "\033[31m $1 is not exist ! \033[0m "
    exit 1
elif
[ ! -e "$2" ] //判斷輸入檔案2是否為存在
then
    echo -e  "\033[31m $2 is not exist ! \033[0m "
    exit 1
elif {
 N1=`awk 'BEGIN{N=0}{N++}END{print N}' $1`   //判斷輸入檔案1、2行數是否對應相等
 N2=`awk 'BEGIN{N=0}{N++}END{print N}' $2`  
[ "$N1" -ne " $N2" ]
}
then

    echo -e "\033[31m $1's lines is not equal to $2's lines ! \033[0m "
    exit 1
fi
#############################Create User#####################################
for LINES in `seq 1 $N1`
do

        USERNAME=`sed -n "${LINES}p" $1`
        PASSWORD=`sed -n "${LINES}p" $2`
        useradd $USERNAME
        [ "$?" -eq "0" ]      //建立使用者返回值為真則建立成功,否則不建立
        echo $PASSWORD | passwd --stadin $USERNAME &> /dev/null && echo $USERNAME created !
done

這裡寫圖片描述

測試:
[root@localhost mnt]# cat userfile 
user1
user2
user3
[root@localhost mnt]# cat passfile 
123
456
[root@localhost mnt]# sh user_create.sh userfile passfile   //行數不相同
 userfile's lines is not equal to passfile's lines !  
[root@localhost mnt]# sh user_create.sh userfile 
 please give me userfile and passfile after script !!    //為加檔案
[root@localhost mnt]# vim passfile 
[root@localhost mnt]# cat passfile   //行數相同
123
789
456
[root@localhost mnt]# sh user_create.sh userfile passfile  
[root@localhost mnt]# id user1
uid=1001(user1) gid=1001(user1) groups=1001(user1)
[root@localhost mnt]# id user2
uid=1002(user2) gid=1002(user2) groups=1002(user2)
[root@localhost mnt]# id user3
uid=1003(user3) gid=1003(user3) groups=1003(user3)    //建立成功
[root@localhost mnt]# vim user_create.sh
[root@localhost mnt]# sh user_create.sh userfile passfile  //使用者已存在,不建立
useradd: user 'user1' already exists
useradd: user 'user2' already exists
useradd: user 'user3' already exists

這裡寫圖片描述

五、case語句

格式:
case $1 in
dog) //第一種情況
echo cat
;;
cat) //第二種情況
echo dog
;;
*) //第三種情況
echo error
esac

實驗一:測試if和case執行次數。

[root@localhost mnt]# cat test.sh    //for語句
#!/bin/bash
if
[ "$1" = "dog" ]  
then

   echo "cat!"
elif
[ "$1" = "cat" ]
then

  echo "dog!"
else

  echo "ERROR: please input "cat" or "dog" follow script !"
fi

[root@localhost mnt]# sh -x test.sh cat   //執行兩次
+ '[' cat = dog ']'
+ '[' cat = cat ']'
+ echo 'dog!'
dog!
[root@localhost mnt]# sh -x test.sh dog  //執行一次
+ '[' dog = dog ']'
+ echo 'cat!'
cat!
[root@localhost mnt]# cat text1.sh   //case語句
#!/bin/bash
case $1 in
        dog)
        echo cat
    ;;
    cat)
    echo dog
    ;;
    *)
    echo error
esac
[root@localhost mnt]# sh -x  text1.sh dog  //執行一次
+ case $1 in
+ echo cat
cat
[root@localhost mnt]# sh -x  text1.sh cat  //執行一次
+ case $1 in
+ echo dog
dog

這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述