linux中until循环,linux中循环语句for,while,until用法linux网页制作 -电脑资料

本文章主要是讲述了关于在linux中的三种循环语句的用法包括了for,while,until用法哦,有需要的朋友参考一下,

循环语句:

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的简化形式,linux中循环语句for,while,until用法linux网页制作》(https://www.unjs.com)。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值