bash编程的循环:while和until
while 测试条件; do
语句1
语句2
...
done
Count=2
if [ $Count -le 5 ]; then
fi
while [ $Count -le 5 ]; do
let Count++
done
条件满足时就循环,直到条件不再满足,则退出循环;
for如何退出循环?遍历列表中的元素完成;
while循环呢?在循环体改变测试条件相应变量等的值。
补充:算术运算符
Sum=$[$Sum+$I]
Sum+=$I
+=
-=
*=
/=
%=
Sum=$[$Sum+1]
Sum+=1
let Sum++
let Count--
and --> AND
exit --> EXIT
quit
计算100以内所有正整数的和;
Sum=0
for I in {1..100}; do
Sum+=$I
done
echo $Sum
#!/bin/bash
Sum=0
Count=1
while [ $Count -le 100 ]; do
let Sum+=$Count
let Count++
done
echo $Sum
计算100以内所有偶数的和;
#!/bin/bash
#
EvenSum=0
Count=0
while [ $Count -le 100 ]; do
let Sum+=$Count
let Count+=2
done
while [ $Count -le 100 ]; do
if [ $[$Count%2] -eq 0 ]; then
Sum+=$Count
fi
let Count++
done
while循环遍历文件的每一行:
while read LINE; do
statement1
statement2
...
done < /path/to/somefile
练习:如果用户的ID号为偶数,则显示其名称和shell;对所有用户执行此操作;
while read LINE; do
Uid=`echo $LINE | cut -d: -f3`
if [ $[$Uid%2] -eq 0 ]; then
echo $LINE | cut -d: -f1,7
fi
done < /etc/passwd
练习:转换用户输入的字符为大写,除了quit(遇见quit退出);
read -p "A string: " String
while [ "$String" != 'quit' ]; do
echo $String | tr 'a-z' 'A-Z'
read -p "Next [quit for quiting]: " String
done
until 测试条件; do
语句1
语句2
...
done
条件不满足就循环,直到满足时,退出循环;
例子:计算100以内所有正整数的和;
Sum=0
Count=1
until [ $Count -gt 100 ]; do
let Sum+=$Count
let Count++
done
echo $Sum
练习:转换用户输入的字符为大写,除了quit(遇见quit退出);
read -p "A string: " String
until [ "$String" == 'quit' ]; do
echo $String | tr 'a-z' 'A-Z'
read -p "Next [quit for quiting]: " String
done
练习:每隔5秒查看hadoop用户是否登录,如果登录,显示其登录并退出;否则,显示当前时间,并说明hadoop尚未登录:
who | grep "^hadoop" &> /dev/null
RetVal=$?
until [ $RetVal -eq 0 ]; do
date
sleep 5
who | grep "^hadoop" &> /dev/null
RetVal=$?
done
echo "hadoop is here."
until who | grep "^hadoop" &> /dev/null; do
date
sleep 5
done
echo "hadoop is here."
who | grep "^hadoop" &> /dev/null
RetVal=$?
while [ $RetVal -ne 0 ]; do
date
sleep 5
who | grep "^hadoop" &> /dev/null
RetVal=$?
done
echo "hadoop is here."
练习:使用while循环统计/etc/rc.d/init.d/functions中#开头的行数;
let Count=0
declare -i Count=0
#!/bin/bash
Count=0
while read LINE ; do
if echo $LINE | grep "^[[:space:]]*#" &> /dev/null ; then
let Count++
fi
done < /etc/rc.d/init.d/functions
echo -e "\n\ttotal $Count lines start with #.\n"
#!/bin/bash
#
Num=0
while read LINE; do
echo $LINE |grep "^#.*" &> /dev/null && let Num++
done < /etc/rc.d/init.d/functions
echo "#Number: $Num"
计算100以内所有偶数的和以及奇数的和;在一个循环中实现;
要求:分别使用while和until各自独立实现。
#!/bin/bash
Evensum=0
Oddsum=0
Count=0
while [ $Count -le 100 ];do
if [ $[$Count%2] -eq 0 ];then
let Evensum+=$Count
else
let Oddsum+=$Count
fi
let Count++
done
echo "The Evensum is : $Evensum"
echo "The Oddsum is : $Oddsum"
#!/bin/bash
Evensum=0
Oddsum=0
Count=0
until [ $Count -gt 100 ]; do
if [ $[$Count%2] -eq 0 ];then
let Evensum+=$Count
else
let Oddsum+=$Count
fi
let Count++
done
echo "The Evensum is : $Evensum"
echo "The Oddsum is : $Oddsum"