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" donebash 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" donefor循环的三个表达式
语法如下:
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 timesfor的无限循环
#!/bin/bash for (( ; ; )) do echo "infinite loops [ hit CTRL+C to stop]" donebreak条件语句
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 donecontinue条件语句
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
原文链接: https://www.cnblogs.com/fhefh/archive/2011/04/15/2017233.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/24069
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!