您的位置:首页 > 运维架构 > Shell

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

2015-10-09 20:00 666 查看
与其他编程语言类似,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux shell shell