(1)while循環
語法:當條件測試成立(真),執行循環體
while 條件測試
do
循環體
done
1)while批量創建用戶1
從user.txt讀取到的行數據賦予給變量user值
#!/bin/bash
while read user
do
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is already exists!"
else
useradd $user
if [ $? -eq 0 ];then
echo "user $user is created!"
fi
fi
done <user.txt
cat user.txt
jack01
jack02
jack03
jack04
2)while批量創建用戶2
while默認空格作為分割,非常適合處理文件
#!/bin/bash
while read line
do
{
user=$(echo $line|awk '{print $1}')
pass=$(echo $line|awk '{print $2}')
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is already exists!"
else
useradd $user
echo $pass | passwd --stdin $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is created!"
fi
fi
}&
done <$1
wait
echo "all ok....."
# cat user2.txt
jack001 123
jack002 123
jack03 123
jack04 123
3)while對有空行文件的處理方式
#!/bin/bash
while read line
do
if [ ${#line} -eq 0 ];then
continue
fi
{
user=$(echo $line|awk '{print $1}')
pass=$(echo $line|awk '{print $2}')
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is already exists!"
else
useradd $user
echo $pass | passwd --stdin $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is created!"
fi
fi
}&
done <$1
wait
echo "all ok....."
(2)until循環
語法:當條件測試成立(假),執行循環體
until 條件測試
do
循環體
done
#!/bin/bash
ip=114.114.114.114
until ping -c1 -W1 $ip &>/dev/null
do
sleep 1
done
echo "$ip is up"
(3)for,while,until 循環ping比較
#!/bin/bash
for i in {2..209}
do
{
ip=192.168.111.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip is up"
fi
}&
done
wait
echo "all done...."
#!/bin/bash
i=2
while [ $i -le 254 ]
do
{
ip=192.168.111.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip is up"
fi
}&
let i++
done
wait
echo "all done...."
#!/bin/bash
i=2
until [ $i -gt 254 ]
do
{
ip=192.168.111.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip is up"
fi
}&
let i++
done
wait
echo "all done...."
(4)for,while,until 循環求1到100的和
#!/bin/bash
for i in {1..100}
do
#let sum=$sum+$i
let sum+=$i
done
echo "sum:$sum"
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
#let sum=$sum+$i
let sum+=$i
let i++
done
echo "sum:$sum"
#!/bin/bash
i=1
until [ $i -gt 100 ]
do
#let sum=$sum+$i
let sum+=$i
let i++
done
echo "sum:$sum"
總結:循環次數固定建議使用for循環,循環文件建議使用while循環,循環次數不固定建議使用while和until循環