while CONDITION; do

statement

...

done



例如:

1.写一个脚本,输入任何字符,小写转换为大写。输入quit退出。

#!/bin/bash

read -p "Input Something" STRING

while [ $STRING != 'quit' ]; do

echo $STRING|tr 'a-z' 'A-Z '

read -p "Input Something" STRING

done


2.写一个脚本,每个5秒检测用户是否登陆,如果登陆则显示已经登陆。

#!/bin/bash

who|grep "hadoop" &> /dev/null

LOG=$?

while [ $LOG -ne 0 ];do

echo `date ,hadoop is not log`

sleep 5

who|grep "hadoop" &> /dev/null

LOG=$?

done

echo "hadoop is logged in"


3.写一个脚本:

显示一个菜单给用户,当用户给定相应选项后显示形影的内容。

#!/bin/bash

cat << EOF

d|D) show disk usages.

m|M) show memory usages.

s|S) show swap usages.

*) quit.

EOF


read -p "your choice:" CHO

while [ $CHO != 'quit' ];do

case  $CHO in

d|D) show disk usages.

echo "disk usages:"

df -h

;;

m|M) show memory usages.

echo "memory usage:"

free- m|grep "Mem"

;;

s|S) show swap usages.

echo "swap usagee:"

free -m| grep "swap"

;;

*) quit.

echo "Unkown"

;;

esac

read -p "your choice again:" CHO

done


while死循环:

while :;do

...

done


例如:

求1至100中奇数的和

#!/bin/bash

let SUM=0

let I=0

while [ $I -lt 100 ];do

if [ $[$I%2] == 0 ];then

continue

fi[r]

let SUM+=$I

done

echo $SUM


while从文件中逐行读取内容并进行处理:

while read LINE;do

...

done < FILE


例如:

输入文件名,判断文件是否存在。

#!/bin/bash

while :;do

read -p "filename"FNAME

[$FNAME == 'quit'] && break

if [ -e $FNAME];then

echo "file exists!"

continue

else

echo "file not exist!"

fi

done