四、 Shell循環語句


1. 循環語句for基本概述

01. for循環基礎語法

for   變量名    in    [ 取值列表 ]
do        
	  循環體
done 

img
02. for循環基本使用示例

#取值列表有多種取值方式,可以直接讀取in后面的值,默認以空格做分割符
[root@cc /scripts]# cat for-1.sh
#!/bin/bash
for var in file1 file2 file3
do
    echo "The text is $var"
done

[root@cc /scripts]# sh for-1.sh
The text is file1
The text is file2
The text is file3

03. for循環基本使用示例,列表中的復雜值,可以使用引號或轉義字符"\"來加以約束

[root@cc /scripts]# cat for-2.sh
#!/bin/bash
for var in file1 "file2 hello" file3
do
    echo "The text is $var"
done

[root@cc /scripts]# sh for-2.sh
The text is file1
The text is file2 hello
The text is file3

#轉義字符
[root@cc /scripts]# cat for-3.sh
#!/bin/bash
for var in file1 file \'2 
do
    echo "The text is $var"
done

[root@cc /scripts]# sh for-3.sh
The text is file1
The text is file
The text is '2

04. for循環基本使用示例,從變量中取值

[root@cc /scripts]# cat for-4.sh
#!/bin/bash
list="file1 file2 file3"
for var in $list
do
    echo $var
done

[root@cc /scripts]# sh for-4.sh
file1
file2
file3

05. for循環基本使用示例,從命令中取值

[root@cc /scripts]# cat for-5.sh
#!/bin/bash
for var in `cat /etc/hosts`
do
    echo $var
done

[root@cc /scripts]# sh for-5.sh
127.0.0.1
localhost
localhost.localdomain
localhost4
localhost4.localdomain4
::1
localhost
localhost.localdomain
localhost6
localhost6.localdomain6

06. for循環基本使用示例,自定義Shell分隔符。默認情況以空格為分隔符。通過IFS來自定義分隔符

#以冒號做分隔符                         IFS=:
#以冒號,分號和雙引號作為字段分隔符          IFS=:;"
#以換行符作為字段分隔符                 IFS=$'\n'


#以回車為換行符
[root@cc /scripts]# cat for-6.sh
#!/bin/bash
IFS=$'\n'
for var in `cat /etc/hosts`
do
    echo $var
done

[root@cc /scripts]# sh for-6.sh
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

#以:為分隔符
[root@cc /scripts]# cat for-7.sh
#!/bin/bash
IFS=:
list=`head -1 /etc/passwd`
for var in $list
do
    echo $var
done

[root@cc /scripts]# sh for-7.sh
root
x
0
0
root
/root
/bin/bash

07. for循環基本使用示例,C語言風格的for

#語法格式
for        ((i=0;i<10;i++))
do
    commands
done

#例1,單個變量,輸出1到10之間的數字
[root@cc /scripts]# cat for-8.sh
#!/bin/bash
for ((i=0;i<10;i++))
do
echo num is $i
done

[root@cc /scripts]# sh for-8.sh
num is 0
num is 1
num is 2
num is 3
num is 4
num is 5
num is 6
num is 7
num is 8
num is 9

#例2,多個變量,同時輸出1-9的升序和降序
#解法一:
[root@cc /scripts]# cat for-9.sh
#!/bin/bash
for ((a=1,b=9;a<10;a++,b--))
do
echo num is $a $b
done

[root@cc /scripts]# sh for-9.sh
num is 1 9
num is 2 8
num is 3 7
num is 4 6
num is 5 5
num is 6 4
num is 7 3
num is 8 2
num is 9 1

#解法二:
[root@cc /scripts]# cat for-10.sh
#!/bin/bash
a=0
b=10
for i in {1..9}
do
let a++;
let b--;
echo num is $a $b
done

[root@cc /scripts]# sh for-10.sh
num is 1 9
num is 2 8
num is 3 7
num is 4 6
num is 5 5
num is 6 4
num is 7 3
num is 8 2
num is 9 1

2. 循環語句for場景示例

01. for循環場景示例一:通過讀入文件中的用戶,進行批量添加用戶。

[root@cc /scripts]# cat for-11.sh
#!/usr/bin/bash
for i in $(cat user.txt) 
do
    useradd $i &>/dev/null
    if [ $? -eq 0 ];then
        echo $i 用戶創建成功
    else
        echo $i 用戶已存在
    fi
done

[root@cc /scripts]# sh for-11.sh
tt1 用戶創建成功
tt2 用戶創建成功
tt3 用戶創建成功
tt4 用戶創建成功
tt5 用戶創建成功
tt6 用戶創建成功
tt7 用戶創建成功
tt8 用戶創建成功
tt9 用戶創建成功
tt10 用戶創建成功

02. for循環場景示例二:通過讀入文件中的用戶:密碼,進行批量添加用戶。

[root@cc /scripts]# cat user.txt
user01:suibian
user02:suibian2
user03:suibian3

[root@cc /scripts]# cat for-12.sh
#!/usr/bin/bash
for i in $(cat user.txt)
do
    #1.取出來的行,使用awk進行分隔,然后分別賦值給user和pass兩個變量
    user=$(echo $i|awk -F ":" '{print $1}')
    pass=$(echo $i|awk -F ":" '{print $2}')
    #2.判斷用戶是否存在
    id $user &>/dev/null
    #3.用戶存在則提示已存在,否則添加用戶,然后使用pass變量設定對應的密碼
    if [ $? -eq 0 ];then
        echo "$user 已存在"
    else
        useradd $user
         echo "$pass" | passwd --stdin $user &>/dev/null
        echo "用戶$user 創建成功!"
    fi
done

[root@cc /scripts]# sh for-12.sh
用戶user1 創建成功!
用戶user2 創建成功!
用戶user3 創建成功!

03. for循環場景示例三:批量創建用戶腳本,需要用戶輸入創建的用戶數量,以及需要用戶輸入創建的前綴。

[root@cc /scripts]# cat for-13.sh
#!/usr/bin/bash
read -p "請輸入你要創建的用戶前綴: " user_qz
read -p "請輸入你要創建的用戶數量: " user_num
echo "你創建的用戶是 ${user_qz}1 ..${user_qz}${user_num}"
read -p "你確定要創建以上用戶嗎?[ y/n ] " readly
case $readly in
    y)
    	for i in $(seq $user_num)
        do
         	user=${user_qz}${i}
        	id $user &>/dev/null
		    	if [ $? -eq 0 ];then
		        	echo "useradd: user $user already exists"
	            else
		            useradd $user
		            echo "useradd: user $user add successfully."
				fi
		 done
		 ;;
    n)
      	  echo "你想好了再創建......"
      	  exit
       	  ;;
    *)
   	     echo "請不要亂輸入...."
     	   exit 1
esac

[root@cc /scripts]# sh for-13.sh
請輸入你要創建的用戶前綴: qiu
請輸入你要創建的用戶數量: 5
你創建的用戶是 qiu1 ..qiu5
你確定要創建以上用戶嗎?[ y/n ] n
你想好了再創建......

[root@cc /scripts]# sh for-13.sh
請輸入你要創建的用戶前綴: qiu
請輸入你要創建的用戶數量: 5
你創建的用戶是 qiu1 ..qiu5
你確定要創建以上用戶嗎?[ y/n ] q
請不要亂輸入....

[root@cc /scripts]# sh for-13.sh
請輸入你要創建的用戶前綴: qiu
請輸入你要創建的用戶數量: 5
你創建的用戶是 qiu1 ..qiu5
你確定要創建以上用戶嗎?[ y/n ] y
useradd: user qiu1 add successfully.
useradd: user qiu2 add successfully.
useradd: user qiu3 add successfully.
useradd: user qiu4 add successfully.
useradd: user qiu5 add successfully.

04. for循環場景示例四:批量創建用戶腳本,需要用戶輸入創建的用戶數量(必須是整數),同時還需要用戶輸入前綴(前綴不能為空)。例如:前綴qls,個數10,代表創建qls1~qls10,總共10個用戶。注意:此腳本僅root可執行,其他人無權限執行。

[root@cc /scripts]# cat for-14.sh
#!/usr/bin/bash
if [ ! $UID -eq 0 ] && [ ! $USER == "root" ];then
    echo "無權限執行......"
    exit
fi

read -p "請輸入你要創建的用戶前綴: " user_qz
if [ -z $user_qz ];then
    echo "請輸入有效的值....."
    exit
fi

read -p "請輸入你要創建的用戶數量: " user_num
if [[ ! $user_num =~ ^[0-9]+$ ]];then
    echo "請輸入整數"
    exit
fi

echo "你創建的用戶是 ${user_qz}1 ..${user_qz}${user_num}"
read -p "你確定要創建以上用戶嗎?[ y/n ] " readly
case $readly in
    y|yes|YES)
        for i in $(seq $user_num)
        do
            user=${user_qz}${i}
            id $user &>/dev/null
            if [ $? -eq 0 ];then
                echo "useradd: user $user already exists"
            else
                useradd $user
                echo "useradd: user $user add successfully."
            fi
        done
        ;;
    n|no|NO)
        echo "你想好了再創建......"
        exit
        ;;
    *)
        echo "請不要亂輸!"
        exit
esac

05. for循環場景示例五:批量創建用戶腳本,需要用戶輸入創建的用戶數量(必須是整數),同時還需要用戶輸入前綴(前綴不能為空)。例如:前綴qls,個數10,代表創建qls1~qls10,總共10個用戶。注意:此腳本僅root可執行,其他人無權限執行。用戶的密碼使用隨機密碼,並保存到某一個指定的文件中。

[root@cc /scripts]# cat for-15.sh
#!/usr/bin/bash
if [ ! $UID -eq 0 ] && [ ! $USER == "root" ];then
    echo "無權限執行......"
    exit
fi

read -p "請輸入你要創建的用戶前綴: " user_qz
if [ -z $user_qz ];then
    echo "請輸入有效的值....."
    exit
fi

read -p "請輸入你要創建的用戶數量: " user_num
if [[ ! $user_num =~ ^[0-9]+$ ]];then
    echo "請輸入整數"
    exit
fi

echo "你創建的用戶是 ${user_qz}1 ..${user_qz}${user_num}"
read -p "你確定要創建以上用戶嗎?[ y/n ] " readly
case $readly in
    y|yes|YES)
        for i in $(seq $user_num)
        do
            user=${user_qz}${i}
            id $user &>/dev/null
            if [ $? -eq 0 ];then
                echo "useradd: user $user already exists"
            else
                user_pass=$(echo $((RANDOM))|md5sum |cut -c 2-10)
                useradd $user
                echo "$user_pass" | passwd --stdin $user &>/dev/null
                echo "用戶: $user 密碼: $user_pass" >> /tmp/user.log
                echo "useradd: user $user add successfully. cat /tmp/user.log"
            fi
        done
        ;;
    n|no|NO)
        echo "你想好了再創建......"
        exit
        ;;
    *)
        echo "請不要亂輸!"
        exit
esac

06. for循環場景示例六:批量刪除(用戶需要輸入用戶前綴及數字),有就刪除,沒有就提示沒有該用戶。

[root@cc /scripts]# cat for-16.sh
#!/usr/bin/bash
if [ ! $UID -eq 0 ] && [ ! $USER == "root" ];then
    echo "無權限執行......"
    exit
fi

read -p "請輸入你要刪除的用戶前綴: " del_qz
if [ -z $del_qz ];then
    echo "請輸入有效的值....."
    exit
fi

read -p "請輸入你要刪除的用戶數量: " user_num
if [[ ! $user_num =~ ^[0-9]+$ ]];then
    echo "請輸入整數"
    exit
fi

echo "你刪除的用戶是 ${del_qz}1 ..${del_qz}${user_num}"
read -p "你確定要刪除以上用戶嗎?[ y/n ] " readly
case $readly in
    y|yes|YES)
        for i in $(seq $user_num)
        do
            user=${del_qz}${i}
            id $user &>/dev/null
            if [ $? -eq 0 ];then
                userdel -r $user
                echo "$user 用戶刪除成功....."
            else
                echo "$user 用戶不存在..."
            fi
        done
        ;;
    n|no|NO)
        echo "你想好了再刪除......"
        exit
        ;;
    *)
        echo "請不要亂輸!"
        exit
esac

[root@cc /scripts]# sh for-16.sh
請輸入你要刪除的用戶前綴: qiu
請輸入你要刪除的用戶數量: 5
你刪除的用戶是 qiu1 ..qiu5
你確定要刪除以上用戶嗎?[ y/n ] y
qiu1 用戶刪除成功.....
qiu2 用戶刪除成功.....
qiu3 用戶刪除成功.....
qiu4 用戶刪除成功.....
qiu5 用戶刪除成功.....

07. for循環場景示例七:批量探測主機存活狀態及22端口狀態

1)需要用循環,循環254次

2)探測主機使用ping命令

[root@cc /scripts]# cat for-17.sh
#!/usr/bin/bash
> /tmp/ip.log
for i in {1..254}
do
    {
    ip=172.16.1.$i
    ping -c 1 -W 1 $ip &>/dev/null
    if [ $? -eq 0 ];then
        echo "$ip is ok"
        echo "$ip is ok" >>/tmp/ip.log
    else
        echo "$ip is down"
    fi
    } &
done
    wait
    echo "Sao Miao IP is Done"
    echo "Test SSH Port Starting......"
IFS=$'\n'
for i in $(cat /tmp/ip.log)
do
    port_ip=$(echo $i |awk '{print $1}')
    nmap $port_ip |grep "22" &>/dev/null
    if [ $? -eq 0 ];then
        echo "$port_ip 22 is ok!!"
        echo "$port_ip 22 is ok!!" >> /tmp/port.log
    fi
done

08. for循環場景示例八:編寫一個上課隨機點名腳本。

1.需要有名字

2.需要循環的打印這些名單

3.隨機挑選一個數字進行打印

[root@cc /scripts]# cat for-18.sh
#!/usr/bin/bash
#1.統計文件的行數
number=$(wc -l /root/student.txt|awk '{print $1}')
#2.整個循環20次
for i in {1..20}
do
    #3.通過random取隨機數,但不超過文件的行數
    stu_num=$((RANDOM % $number + 1 ))
    #4.循環一次打印一次隨機的名
    sed -n "${stu_num}p" /root/student.txt
    #5.等待0.1s之后再循環下一次
    sleep 0.10
done
    #6.將最后一次循環提取的人名賦值給name_stu
    name_stu=$(sed -n "${stu_num}p" /root/student.txt)
    #7.自定義輸出人名,外加顏色,好看。
    echo -e "天選子: \033[32m ${name_stu}....\033[0m"

09. for循環場景示例九:使用for循環實現數據庫的分庫分表備份。

1.怎么備份數據庫

 mysqldump -uroot -p123.com --single-transaction -B world > world_database.sql

2.怎么備份數據庫的表

mysqldump -uroot -p123.com --single-transaction world city > world_city_tables.sql

3.備份到哪兒

/mysql_dump/oldboy/city_2019_07_16.sql
#!/usr/bin/bash
db_name=$(mysql -uroot -p123.com -e "show databases;"|sed 1d |grep -v ".*_schema")_
DB_User=root
DB_Pass=123.com
Date=$(date +%F)
for database_name in $db_name
do
    #1.准備每個庫的目錄
    DB_Path=/mysql_dump/$database_name
    if [ ! -d $DB_Path ];then
        mkdir -p $DB_Path
    fi
    #2.備份數據庫
    mysqldump -u$DB_User -p$DB_Pass --single-transaction \
    -B $database_name > $DB_Path/${database_name}_${Date}.sql
    	echo -e "\033[31m $database_name 數據庫已經備份完成..... \033[0m"
     #3.備份數據庫的每一個表
     tb_name=$(mysql -u$DB_User -p$DB_Pass -e "use ${database_name};show tables;"|sed 1d)        
	#4.批量的備份數據庫的表
    for table_name in $tb_name
    do
        #5.備份數據庫的表數據
        mysqldump -u$DB_User -p$DB_Pass --single-transaction \
        $database_name $table_name > $DB_Path/${database_name}_${table_name}_tables_${Date}.sql
        echo -e "\033[32m 備份$database_name 的數據庫中的 $table_name 數據表,備份成功 \033[0m"
    done
done

10. for循環場景示例十:用於判斷mysql數據庫主從的腳本,需要郵件通知。

1.判斷io線程和sql線程是否都為yes,如果是則成功。

2.如果io線程失敗,則直接郵件通知,如果sql線程失敗,則檢查是什么錯誤狀態碼,根據狀態碼修復。

3.無法修復,或任何錯誤代碼太復雜建議,直接發郵件通知管理員。

[root@cc /scripts]# cat for-20.sh
#!/usr/bin/bash
IO_Status=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Slave_IO_Running/ {print $2}')
SQL_Status=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Slave_SQL_Running/ {print $2}')
slave_sql_error_message(){
    mysql -uroot -p123.com -e "show slave status\G"|grep "Last_SQL" > /tmp/sql_err.log   
	mail -s "MySQL Master SLave SQL Error $(date +%F)" 1176494252@qq.com < /tmp/sql_err.log
    echo "郵件通知成功......"
}

slave_io_error_message(){
    mysql -uroot -p123.com -e "show slave status\G"|grep "Last_IO" > /tmp/io_err.log
    mail -s "MySQL Master SLave IO Error $(date +%F)" 1176494252@qq.com < /tmp/io_err.log
    echo "郵件通知成功......"
}

if [ $IO_Status == "Yes" ] && [ $SQL_Status == "Yes" ];then
    echo "MySQL主從正常"
else
    #1.判斷IO異常
    if [ ! $IO_Status == "Yes" ];then
        slave_io_error_message
        exit
     fi
    #2.判斷SQL異常
    if [ ! $SQL_Status == "Yes" ];then
        SQL_Err=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Last_SQL_Errno/ {print $2}')
        #3.精細化判斷主從不同步的問題
        case $SQL_Err in
             1007) 
                echo "主從的SQL出現問題,嘗試使用set global sql_slave_skip_counter=1; 跳過錯誤"
                sleep 2
                mysql -uroot -p123.com -e "stop slave;set global sql_slave_skip_counter=1;start slave;" 
                SQL_Err_1=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Last_SQL_Errno/ {print $2}')
                if [ $SQL_Err_1 -eq 0 ];then
                    echo "嘗試跳過了一次,恢復MySQL數據庫成功"
                else
                    slave_sql_error_message
                fi
                 ;;
            1032)
                 slave_sql_error_message
                 ;;
            *)
                 slave_sql_error_message
        esac
    fi
fi

3. 循環語句while基本概述

while循環語句,只要條件成立就反復執行對應的命令操作,直到命令不成立或為假

01. while循環基礎語法

#當條件測試成立(條件測試為真),執行循環體
while 條件測試
do          循環體
done 

img
02. while循環基本使用示例,降序輸出10到1的數字

[root@cc /scripts]# cat while-1.sh
#!/bin/bash
var=10
while [ $var -gt 0 ]
do
    echo $var
    var=$[$var-1]
done

#簡單加法表
[root@cc /scripts]# cat while-2.sh
#!/usr/bin/bash
a=1
b=10
while [ $a -le 10 ]
do
    sum=$(( $a + $b ))
    echo $a + $b = $sum
    let a++
    let b--
done

03. while循環基本使用示例,輸出如下圖,兩數相乘。

#自增
[root@cc /scripts]# cat while-3.sh
#!/bin/bash
num=9
while [ $num -ge 1 ]
do
    sum=$(( $num * $num ))
    echo "$num * $num = $sum"
    num=$[$num-1]
done

#自減
[root@cc /scripts]# cat while-4.sh
#!/bin/bash
num=1
while [ $num -le 9 ]
do
    sum=$(( $num * $num ))
    echo "$num * $num = $sum"
    num=$[$num+1]
done

4. 循環語句while場景示例

01. 使用while讀入文件方式,批量創建用戶,while默認按行取值

[root@cc /scripts]# cat while-5.sh
#!/usr/bin/bash
while read line
do
    #1.判斷用戶是否存在
    id $line &>/dev/null
    if [ $? -eq 0 ];then
        echo "User: $line already exists"
    else
        useradd $line &>/dev/null
        echo "User: $line Create Ok"
    fi
done<user.txt

[root@cc /scripts]# cat user.txt
ttt1
ttt2
ttt3
ttt4
ttt5

02. 使用while讀入文件方式,批量創建用戶以及密碼[user:passwd]

[root@cc /scripts]# cat while-6.sh
#!/usr/bin/bash
while read line
do
    user=$(echo $line |awk -F ':' '{print $1}')
    pass=$(echo $line |awk -F ':' '{print $2}')
    id $user &>/dev/null
    if [ $? -eq 0 ];then
        echo "用戶已存在"
    else
        useradd $user && \
        echo $pass |passwd --stdin $user &>/dev/null
        echo "用戶: $user is ok 密碼: $pass "
    fi
done<user.txt

[root@cc /scripts]# cat user.txt
tttt1:ggdfg
tttt2:fbthb
tttt3:fbtbht
tttt4:bthht
tttt5:frgt

03. 使用while讀入文件方式,批量創建用戶,並賦予一個隨機密碼

[root@cc /scripts]# cat while-7.sh
#!/usr/bin/bash
while read line
do
    pass=$(echo $RANDOM |md5sum |cut -c1-10)
    id $line &>/dev/null
    if [ $? -eq 0 ];then
        echo "用戶已存在"
    else
        useradd $line && \
        echo $pass |passwd --stdin $line &>/dev/null
        echo "用戶: $line is ok 密碼: $pass "
    fi
done<user.txt

04. while循環場景示例:完成如下猜數字游戲

  1. 隨機輸出一個1-100的數字 echo $((RANDOM % 100 + 1 ))

  2. 要求用戶輸入的必須是數字(數字處加判斷)

  3. 如果比隨機數小則提示比隨機數小了
    大則提示比隨機數大了

  4. 正確則退出
    錯誤則繼續死循環

  5. 最后統計總共猜了多少次(成功多少次,失敗多少次)

#!/usr/bin/bash
 sj=$(echo $((RANDOM % 100 + 1 )))
 i=0
 while true
 do
     read -p "請輸入一個你需要猜的數字: " cc
     if [[ ! $cc =~ ^[0-9]+$ ]];then
         echo "請輸入整數"
         continue
     fi 
    #將用戶的輸入的數字與隨機數進行比較
    if [ $cc -gt $sj ];then
         echo "你猜的太大"
     elif
 [ $cc -lt $sj ];then
         echo "你猜的太小,繼續加油"
     else
         echo "猜對了....."
         break
     fi
     #進行數值自增
    let i++
 done
     echo "你總共失敗了多少次 $i"
     echo "你總共猜了多少次 $(( $i + 1 ))"

05. while循環場景示例:隨機點菜腳本

菜單顯示以下內容

#!/bin/bash
menu(){
echo -e "*********************************" 
echo -e "*    1.青椒土豆絲\t\t*"
echo -e "*    2.麻婆豆腐\t\t*"
echo -e "*    3.紅燒大盤雞\t元\t*" 
echo -e "*    4.宮保雞丁\t\t*" 
echo -e "*    5.魚香肉絲\t\t*"
echo -e "*    6.西紅柿雞蛋\t\t*" 
echo -e "*    7.紅燒肉\t\t*" 
echo -e "*    8.酸菜魚\t元\t*" 
echo -e "*    9.結束點菜\t\t*" 
echo -e "*********************************" 
} 

num=`echo $((RANDOM%9+1))` 
while true
do
	menu
	read -p "請開始點菜:" num
 	case $num in
     1)
         echo "您點了青椒土豆絲"
         ;;
     2)
         echo "您點了麻婆豆腐"
         ;;
     3)
         echo "您點了紅燒大盤雞"
		 ;;
     4)
         echo "您點了宮保雞丁"
		 ;;
     5)
         echo "您點了魚香肉絲"
		 ;;
     6)
         echo "您點了西紅柿雞蛋"
 	 	 ;;
     7)
         echo "您點了紅燒肉"
 		 ;;
     8)
         echo "您點了酸菜魚"
		 ;;
     9)
         echo "稍等,馬上上菜!"
		 exit
	esac
done 

5. 內置跳出循環語句指令

在我們使用循環語句進行循環的過程中,有時候需要在未達到循環結束條件時強制跳出循環,那么Shell給我們提供了內置方法來實現該功能:exit、break、continue

01. exit,退出整個程序

[root@cc /scripts]# cat for-exit.sh
#!/bin/bash
for i in {1..3}
do
echo "123"
exit
echo "456"
done
echo "done ......"

#執行結果
[root@cc /scripts]# sh for-exit.sh
123

02. break,結束當前循環,或跳出本層循環

[root@cc /scripts]# cat for-break.sh
#!/bin/bash
for i in {1..3}
do
echo "123"
break
echo "456"
done
echo "done ......"

#執行結果
[root@cc /scripts]# sh for-break.sh
123
done ......

img
03. continue,忽略本次循環剩余的代碼,直接進行下一次循環。

[root@cc /scripts]# cat for-continue.sh
#!/bin/bash
for i in {1..3}
do
echo "123"
continue
echo "456"
done
echo "done ......"

#執行結果
[root@cc /scripts]# sh for-continue.sh
123
123
123
done ......

img
04. 習題:先掃描內網網段所有主機,存活的則下發當前主機的公鑰。

[root@cc /scripts]# cat key.sh 
#!/bin/bash 
#刪除舊的密鑰對
rm -f ~/.ssh/id_rsa* 

#創建密鑰對
ssh-keygen -t rsa -f ~/.ssh/id_rsa -N "" &>/dev/null 

#批量分發公鑰的操作
for ip in {2..10} 
do
	ping -W1 -c1 172.16.1.$ip &>/dev/null
	if [ $? -eq 0 ];then
    	sshpass -p123 ssh-copy-id -p2222 -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.$ip &>/dev/null
     	if [ $? -eq 0 ];then
        	echo -e "\033[32mhost 172.16.1.$ip Distribution of the secret key Success!!! \033[0m"         
			echo
     	else
        	echo -e "\033[31mhost 172.16.1.$ip Distribution of the secret key Failed !!! \033[0m"
        	echo
        fi
 	else
    	echo -e "\033[31mhost 172.16.1.$ip Destination Host Unreachable! \033[0m"
    	continue
 	fi
done 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM