文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>linux shell循环示例

linux shell循环示例

时间:2011-04-15  来源:fhefh

for循环示例

for循环语法:

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

 

#!/bin/bash

for i in 1 2 3 4 5

do

echo "Welcome $i times"

done

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

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载