Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2977445
  • 博文数量: 401
  • 博客积分: 12926
  • 博客等级: 上将
  • 技术积分: 4588
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-22 14:51
文章分类

全部博文(401)

文章存档

2015年(16)

2014年(4)

2013年(12)

2012年(82)

2011年(98)

2010年(112)

2009年(77)

分类: Python/Ruby

2011-06-29 18:20:47

for循环示例

for循环语法:

1for VARIABLE in 1 2 3 4 5 .. N
2do
3         command1
4         command2
5         commandN
6done

 

01#!/bin/bash
02 
03for i in 1 2 3 4 5
04 
05do
06 
07echo "Welcome $i times"
08 
09done
10

bash version 3.0+版本
#!/bin/bash
 for i in {1..5}
do
   echo "Welcome $i times"
done

bash version 4版本 

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done

含有“seq”命令的语法示例

#!/bin/bash
for i in $(seq 1 2 20)
do
   echo "Welcome $i times"
done

for循环的三个表达式

语法如下:

for (( EXP1; EXP2; EXP3 ))
do
         command1
         command2
         command3
done

示例如下:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do
         echo "Welcome $c times..."
done

效果:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

for的无限循环

#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

break条件语句

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (disaster-condition)
  then
         break                #Abandon the loop.
  fi
  statements3          #While good and, no disaster-condition.
done

下面的shell脚本将通过在/ etc目录中存储的所有文件。 for循环将放弃当/ etc / resolv.conf的文件中找到。

#!/bin/bash
for file in /etc/*
do
         if [ "${file}" == "/etc/resolv.conf" ]
         then
                 countNameservers=$(grep -c nameserver /etc/resolv.conf)
                 echo "Total  ${countNameservers} nameservers defined in ${file}"
                 break
         fi
done

continue条件语句

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (condition)
  then
         continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

利用这个脚本在命令行中指定的所有文件名的备份。如果。bak文件存在,它会跳过cp命令。

#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
         if [ -f ${f}.bak ]
         then
                 echo "Skiping $f file..."
                 continue  # read next file and skip cp command
         fi
        # we are hear means no backup file exists, just use cp command to copy file
         /bin/cp $f $f.bak
done

阅读(1789) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~