天天看點

Shell---for循環for 循環while 和 util

版權聲明:本文為部落客原創文章,轉載請注明出處。 https://blog.csdn.net/twilight_karl/article/details/78373112

for 循環

文法一:

for 變量 in value1 value2 value3...
    do 
        // do something
    done           

文法二 :

for (( 初始值;循環控制條件;變量變化 ))
    do
        // do something
    done           

案例一:

#!/bin/bash

for i in 1 2 3 4 5
        do
                echo $i
        done           

案例二:

#!/bin/bash

result=0
for ((i=1;i<=100;i=i+1))
        do
                result=$(($result+$i))
        done
echo $result            

案例三,批量添加使用者:

#!/bin/bash

read -p "請輸入使用者名:" name
read -p "請輸入建立使用者的數量" number
read -p "請輸入密碼:" password

if [ -n "$name" -a -n "$number" -a -n "$password" ]
        then
                # 判斷數量是否是數字
                flag=`echo $number | sed "s/[0-9]//g" `
                if [ -n flag ]
                        then
                        for (( i=1;i<=$number;i=i+1 ))
                                        do
                                                /usr/sbin/useradd $name$i
                                                echo $passwd | /usr/bin/passwd --stdin $name$i
                                                echo "成功添加使用者$name$i,密碼$passwd\n"        
                                        done
                fi
else
        echo "不能為空"
fi           

案例四,批量删除使用者:

#!/bin/bash

# 批量删除使用者
read -p "請輸入需要删除的使用者名:" name

list=$(cat /etc/passwd | grep $name | cut -d ":" -f 1)

for i in $list
        do
                userdel $i
        done                 

while 和 util

文法:

# 條件滿足時執行循環
while [ 條件判斷式 ]
    do 
        // do something
    done           
# 條件滿足時退出循環
until [  條件判斷式 ]
    do 
        // do something
    done            

案例五:

[root@localhost sh]# vim while.sh 

#!/bin/bash

# 測試while循環

i=1
s=0
while [ "$i" -le 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done
echo $s           

案例六:

#!/bin/bash

i=1
s=0

until [ "$i" -gt 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done
echo $s