天天看點

Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

一、三個腳本退出語句

Exit 結束腳本,整體退出

Break 允許跳出所有循環(終止執行後面的所有循環)

Continue 提前結束目前循環,進入下一個循環

為了更清楚的了解這幾個的差別進行以下實驗:

root@desktop26 mnt]# cat test1.sh 
#######################################
# Author:       yifan                 #
# Version:                            #
# Mail:                               #
# Date:         --//      #
# Description:                        #
#                                     #
#######################################

#!/bin/bash
for NUM in {}          //從1到4循環
do
        if 
        [ "$NUM " -eq   ]  //判斷NUM是否等于3
    then  
          $      //這裡輸入腳本後輸入的三個測試值
    fi
    echo $NUM      
done
echo hello
[root@desktop26 mnt]# sh  test1.sh exit    //當NUM=3後直接全部退出腳本


[root@desktop26 mnt]# sh test1.sh continue  //當NUM=3後,不執行後面的“echo NUM”,直接進入下次循環




hello
[root@desktop26 mnt]# sh  test1.sh break  //結束for的所有循環,進入下一步指令“echo hello”


hello
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

二、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}
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 





[root@desktop26 mnt]# vim test2.sh
[root@desktop26 mnt]# cat test2.sh 
#!/bin/bash
for NUM in `seq  `
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 





[root@desktop26 mnt]# vim test2.sh
[root@desktop26 mnt]# cat test2.sh 
#!/bin/bash
for NUM in `seq   `  //從1到5,步長為2,即1.3.5.
do
        echo $NUM  
done
[root@desktop26 mnt]# sh  test2.sh 



           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

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

#!/bin/bash
for HOSTNUMBER in `seq  `
do
   ping -c1 -w1 .$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 
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is down;
  is up;
  is up;
  is down;
  is up;
  is up;
  is down;
  is up;
  is up;
  is up;
  is down;
  is up;
  is down;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is down;
  is up;
  is up;
  is down;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is up;
  is down;
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

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

1.建立資料庫:

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

Copyright (c) , , 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,  row affected ( sec)

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

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

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

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

MariaDB [linux]> quit
Bye
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

2.編寫腳本如下:

Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

三、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  ] && {
                echo "Your / will full !" | mail -s warning root
        }
        sleep     //每隔1秒執行一次
done                                                   
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
root@node1 mnt]# df  //檢視根分區使用情況
Filesystem           Used Available Use% Mounted on
/dev/vda1           10473900 9488536    985364  29% /
devtmpfs                            % /dev
tmpfs                              % /dev/shm
tmpfs                           % /run
tmpfs                               % /sys/fs/cgroup
/dev/mapper/vg0-vo               % /home
[root@node1 mnt]# sh test.sh &  //執行腳本,并打入背景
[] 
[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                            % /dev
tmpfs                              % /dev/shm
tmpfs                           % /run
tmpfs                               % /sys/fs/cgroup
/dev/mapper/vg0-vo               % /home
[root@node1 mnt]# sh test.sh &  //執行腳本并打入背景
[] 
[root@node1 mnt]# mail  //可以查到郵件
Heirloom Mail version  //  Type ? for help."/var/spool/mail/root":  messages  new
>N   root                  Thu Jun  :  /   "warning"
 N   root                  Thu Jun  :  /   "warning"
 N   root                  Thu Jun  :  /   "warning"
 N   root                  Thu Jun  :  /   "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 $
fi
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

測試:

[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 

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

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

        USERNAME=`sed -n "${LINES}p" $`
        PASSWORD=`sed -n "${LINES}p" $`
        useradd $USERNAME
        [ "$?" -eq "0" ]      //建立使用者傳回值為真則建立成功,否則不建立
        echo $PASSWORD | passwd --stadin $USERNAME &> /dev/null && echo $USERNAME created !
done
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

測試:

[root@localhost mnt]# cat userfile 
user1
user2
user3
[root@localhost mnt]# cat passfile 


[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   //行數相同



[root@localhost mnt]# sh user_create.sh userfile passfile  
[root@localhost mnt]# id user1
uid=(user1) gid=(user1) groups=(user1)
[root@localhost mnt]# id user2
uid=(user2) gid=(user2) groups=(user2)
[root@localhost mnt]# id user3
uid=(user3) gid=(user3) groups=(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
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

五、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 $ in
        dog)
        echo cat
    ;;
    cat)
    echo dog
    ;;
    *)
    echo error
esac
[root@localhost mnt]# sh -x  text1.sh dog  //執行一次
+ case $ in
+ echo cat
cat
[root@localhost mnt]# sh -x  text1.sh cat  //執行一次
+ case $ in
+ echo dog
dog
           
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句
Linux——for、while、if、case四大shell語句簡單舉例一、三個腳本退出語句二、for語句三、while語句四、If語句五、case語句

繼續閱讀