一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

linux中循环语句for,while,until用法

时间:2022-11-14 22:04:19 编辑:袖梨 来源:一聚教程网

循环语句:
Bash Shell中主要提供了三种循环方式:for、while和until。
for循环声明格式:

代码如下 复制代码
for variable in word_list
do
command
done

见如下示例脚本:

代码如下 复制代码
/> cat > test7.sh
for score in math english physics chemist #for将循环读取in后面的单词列表,类似于Java的for-each。
do
echo "score = $score"
done
echo "out of for loop"
CTRL+D
/> . ./test7.sh
score = math
score = english
score = physics
score = chemist
out of for loop

/> cat > mylist #构造数据文件
tom
patty
ann
jake
CTRL+D
/> cat > test8.sh
#!/bin/sh
for person in $(cat mylist) #for将循环读取cat mylist命令的执行结果。
do
echo "person = $person"
done
echo "out of for loop."
CTRL+D
/> . ./test8.sh
person = tom
person = patty
person = ann
person = jake
out of for loop.

/> cat > test9.sh
for file in test[1-8].sh #for将读取test1-test8,后缀为.sh的文件
do
if [ -f $file ] #判断文件在当前目录是否存在。
then
echo "$file exists."
fi
done
CTRL+D
/> . ./test9.sh
test2.sh exists.
test3.sh exists.
test4.sh exists.
test5.sh exists.
test6.sh exists.
test7.sh exists.
test8.sh exists.

/> cat > test10.sh
for name in $* #读取脚本的命令行参数数组,还可以写成for name的简化形式。
do
echo "Hi, $name"
done
CTRL+D
/> . ./test10.sh stephen ann
Hi, stephen
Hi, ann



while循环声明格式:

代码如下 复制代码
while command #如果command命令的执行结果为0,或条件判断为真时,执行循环体内的命令。
do
command
done

见如下示例脚本:

代码如下 复制代码
/> cat > test1.sh
num=0
while (( num < 10 )) #等同于 [ $num -lt 10 ]
do
echo -n "$num "
let num+=1
done
echo -e "nHere's out of loop."
CTRL+D
/> . ./test1.sh
0 1 2 3 4 5 6 7 8 9
Here's out of loop.

/> cat > test2.sh
go=start
echo Type q to quit.
while [[ -n $go ]] #等同于[ -n "$go" ],如使用该风格,$go需要被双引号括起。
do
echo -n How are you.
read word
if [[ $word == [Qq] ]] #等同于[ "$word" = Q -o "$word" = q ]
then
echo Bye.
go= #将go变量的值置空。
fi
done
CTRL+D
/> . ./test2.sh
How are you. Hi
How are you. q
Bye.



until循环声明格式:
until command #其判断条件和while正好相反,即command返回非0,或条件为假时执行循环体内的命令。
do
command
done
见如下示例脚本:
/> cat > test3.sh
until who | grep stephen #循环体内的命令将被执行,直到stephen登录,即grep命令的返回值为0时才退出循环。

代码如下 复制代码
do
sleep 1
echo "Stephen still doesn't login."
done
CTRL+D

热门栏目