linux循环控制结构,Linux Shell 之 Shell 基本控制结构(二)(循环结构)

与其他编程语言类似,Shell支持for循环,和while 循环。

1、for 循环

for循环一般格式为:

for 变量 in 列表

do

command1

command2

...

commandN

done

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

#!/bin/bash

#数字段形式

for i in {1..10}

do

echo $i

done

#详细列出(字符且项数不多)

for File in 1 2 3 4 5

do

echo $File

done

#对存在的文件进行循环

for shname in `ls *.sh`

do

name=`echo "$shname" | awk -F. '{print $1}'`

echo $name

done

#查找循环(ls数据量太大的时候也可以用这种方法)

for shname in `find . -type f -name "*.sh"`

do

name=`echo "$shname" | awk -F/ '{print $2}'`

echo $name

done

#((语法循环--有点像C语法,但记得双括号

for((i=1;i<100;i++))

do

if((i%3==0))

then

echo $i

continue

fi

done

#seq形式 起始从1开始

for i in `seq 100`

do

if((i%3==0))

then

echo $i

continue

fi

done

2、while 循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while command

do

Statement(s) to be executed if command is true

done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。

#while循环注意为方括号[],且注意空格

min=1

max=100

while [ $min -le $max ]

do

echo $min

min=`expr $min + 1`

done

#双括号形式,内部结构有点像C的语法,注意赋值:i=$(($i+1))

i=1

while(($i<100))

do

if(($i%4==0))

then

echo $i

fi

i=$(($i+1))

done

#从配置文件读取,并可以控制进程数量

MAX_RUN_NUM=8

cat cfg/res_card_partition.cfg |grep -v '^$'|grep -v "#" | grep -v grep |while read partition

do

nohup sh inv_res_card_process.sh $partition >log/resCard$partition.log 2>&1 &

while [ 1 -eq 1 ]

do

psNum=`ps -ef | grep "inv_res_card_process" | grep -v "grep" | wc -l`

if [ $psNum -ge $MAX_RUN_NUM ]

then

sleep 5

else

break

fi

done

done

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值