linux while 循环

Bash While 循环实例

13. 07.

Bash While Loop Example – Bash While 循环实例

Q. How do I use bash while loop to repeat certain task under Linux / UNIX operating system?
A. Bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.
while loop syntax

while [ condition ]
do
command1
command2
command3
done

command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. For example following while loop will print welcome 5 times on screen:

#!/bin/bash
x=1
while [ $x -le 5 ]
do
echo "Welcome $x times"
x=$(( $x + 1 ))
done

Here is a sample shell code to calculate factorial using while loop:

#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial

To run just type:

$ chmod +x script.sh
$ ./script.sh 5

Output:

120

While loops are frequently used for reading data line by line from file:

#!/bin/bash
FILE=$1
# read $FILE using the file descriptors
exec 3exec 0while read line
do
# use $line variable to process line
echo $line
done
exec 0

You can easily evaluate the options passed on the command line for a script. using while loop:

......
..
while getopts ae:f:hd:s:qx: option
do
case "${option}"
in
a) ALARM="TRUE";;
e) ADMIN=${OPTARG};;
d) DOMAIN=${OPTARG};;
f) SERVERFILE=$OPTARG;;
s) WHOIS_SERVER=$OPTARG;;
q) QUIET="TRUE";;
x) WARNDAYS=$OPTARG;;
\?) usage
exit 1;;
esac
done
.......
..

作者: hao32 | 可以转载, 转载时务必以超链接形式标明文章 原始出处和作者信息及版权声明
网址: http://www.hao32.com/unix-linux/92.html

Tags: bash, shell, while, 循环

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/90618/viewspace-668909/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/90618/viewspace-668909/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值