Linux shell中while循环是怎样的(linux,shell,while,开发技术)

时间:2024-05-04 10:26:09 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

在shell中while循环也是一个常用的循环结构,和其他语言的语法有许多类似之处,但是也有个别地方不一样。

常用格式

格式一

while 条件;

do

语句

done

格式二 死循环

while true

do

语句

done

格式三 死循环

while :

do

语句

done

格式四 死循环

while [ 1 ]

do

语句

done

格式五 死循环

while [ 0 ]

do

语句

done

使用示例

示例一

Bash代码 Linux shell中while循环是怎样的

  1. COUNTER=0

  2. while [ $COUNTER -lt 10 ]; do

  3. echo The counter is $COUNTER

  4. let COUNTER=COUNTER+1

  5. done

[root@jfht ~]# COUNTER=0[root@jfht ~]# while [ COUNTER> let COUNTER=COUNTER+1> doneThe counter is 0The counter is 1The counter is 2The counter is 3The counter is 4The counter is 5The counter is 6The counter is 7The counter is 8The counter is 9[root@jfht ~]#

这个while循环改用for循环更好些

Bash代码 Linux shell中while循环是怎样的

  1. for ((COUNTER=0; COUNTER

  2. do

  3. echo The counter is $COUNTER

  4. done

[root@jfht ~]# for ((COUNTER=0; COUNTER> do> echo The counter is $COUNTER> doneThe counter is 0The counter is 1The counter is 2The counter is 3The counter is 4The counter is 5The counter is 6The counter is 7The counter is 8The counter is 9[root@jfht ~]#

示例二

Bash代码

  1. while true

  2. do

  3. date

  4. sleep 1

  5. done

[root@jfht ~]# while true> do> date> sleep 1> done2010年 10月 10日 星期日 16:35:22 CST2010年 10月 10日 星期日 16:35:23 CST2010年 10月 10日 星期日 16:35:24 CST2010年 10月 10日 星期日 16:35:25 CST2010年 10月 10日 星期日 16:35:26 CST2010年 10月 10日 星期日 16:35:27 CSTCtrl+C[root@jfht ~]#

示例三 读取输入

Java代码 Linux shell中while循环是怎样的

  1. while read line

  2. do

  3. echo $line

  4. done

[root@jfht ~]# while read line> do> echo $line> donehellohelloworldworldCtrl+D[root@jfht ~]#

实例四 处理命令行参数

文件 while_4.sh

Bash代码


#!/bin/shusage(){echo“usage:$0[-a][-e][-f][-h][-d][-s][-q][-x]”}whilegetoptsae:f:hd:s:qx:optiondocase“${option}”ina)ALARM=”TRUE”;;e)ADMIN=${OPTARG};;d)DOMAIN=${OPTARG};;f)SERVERFILE=$OPTARG;;s)WHOIS_SERVER=$OPTARG;;q)QUIET=”TRUE”;;x)WARNDAYS=$OPTARG;;\?)usage;exit1;;esacdoneecho“ALARM=$ALARM”echo“ADMIN=$ADMIN”[root@jfht~]#catwhile_4.sh#!/bin/shusage(){echo“usage:$0[-a][-e][-f][-h][-d][-s][-q][-x]”}whilegetoptsae:f:hd:s:qx:optiondocase“{OPTARG};;d)DOMAIN=OPTARG;;s)WHOIS_SERVER=OPTARG;;\?)usage;exit1;;esacdoneecho“ALARM=ADMIN”[root@jfht~]#chmod+xwhile_4.sh[root@jfht~]#./while_4.shALARM=ADMIN=[root@jfht~]#./while_4.sh-aALARM=TRUEADMIN=[root@jfht~]#./while_4.sh-ehyALARM=ADMIN=hy
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Linux shell中while循环是怎样的的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Linux怎么安装autojump下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18