There are two types of bash for loops available. One using the “in” keyword with list of values, another using the C programming like syntax.
      This article is part of our on-going bash tutorial series.
      This explains both of the bash for loop methods, and provides 12 different examples on how to use the bash for loop in your shell scripts.
      Bookmark this article for future reference, as this is the only article you would ever need to refer on how to use bash for loops with examples.
      Method 1: Bash For Loop using “in” and list of values
 
      Syntax:
 
      for varname in list
      do
          command1
          command2
          ..
      done
      In the above syntax:
 
      for, in, do and done are keywords
      “list” contains list of values. The list can be a variable that contains several words separated by spaces. If list is missing in the for statement, then it takes the positional parameter that were passed into the shell.

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      varname is any Bash variable name.
      In this form, the for statement executes the commands enclosed in a body, once for each item in the list. For example, if the list of values contains 5 items, the for loop will be executed a total of 5 times, once for each item in the list. The current item from the list will be stored in a variable “varname” each time through the loop. This “varname” can be processed in the body of the for loop.
 
      Method 2: Bash For Loop using C like syntax
 
      The second form of the for loop is similar to the for loop in “C” programming language, which has three expressions (initialization, condition and updation).
 
      for (( expr1; expr2; expr3 ))
      do
          command1
          command2
          ..
      done
      In the above bash for command syntax,
 
      Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop.
      All the statements between do and done are executed repeatedly until the value of expr2 is TRUE.
      After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop counter.
      The following 12 examples shows how to bash for loops in different ways.
 
      1. Static values for the list after “in” keyword
 
      In the following example, the list of values (Mon, Tue, Wed, Thu and Fri) are directly given after the keyword “in” in the bash for loop.

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

 
      $ cat for1.sh
      i=1
      for day in Mon Tue Wed Thu Fri
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for1.sh
      Weekday 1 : Mon
      Weekday 2 : Tue
      Weekday 3 : Wed
      Weekday 4 : Thu
      Weekday 5 : Fri
      Caution: The list of values should not be separated by comma (Mon, Tue, Wed, Thu, Fri). The comma will be treated as part of the value. i.e Instead of “Mon”, it will use “Mon,” as value as shown in the example below.
 
      $ cat for1-wrong1.sh
      i=1
      for day in Mon, Tue, Wed, Thu, Fri
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for1-wrong1.sh
      Weekday 1 : Mon,
      Weekday 2 : Tue,
      Weekday 3 : Wed,
      Weekday 4 : Thu,
      Weekday 5 : Fri
      Caution: The list of values should not be enclosed in a double quote. (“Mon Tue Wed Thu Fri”). If you enclose in double quote, it will be treated as a single value (instead of 5 different values), as shown in the example below.
 
      $ cat for1-wrong2.sh

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      i=1
      for day in "Mon Tue Wed Thu Fri"
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for1-wrong2.sh
      Weekday 1 : Mon Tue Wed Thu Fri
      2. Variable for the list after “in” keyword
 
      Instead of providing the values directly in the for loop, you can store the values in a variable, and use the variable in the for loop after the “in” keyword, as shown in the following example.
 
      $ cat for2.sh
      i=1
      weekdays="Mon Tue Wed Thu Fri"
      for day in $weekdays
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for2.sh
      Weekday 1 : Mon
      Weekday 2 : Tue
      Weekday 3 : Wed
      Weekday 4 : Thu
      Weekday 5 : Fri
      Caution: As a best practice, you should always quote the bash variables when you are referring it. There are few exceptions to this best practice rule. This is one of them. If you double quote the variable in this for loop, the list of values will be treated as single value. Lot of people fall into this trap. Be careful and do not double quote your variable in the for loop.
 
      $ cat for2-wrong.sh
      i=1
      weekdays="Mon Tue Wed Thu Fri"

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      for day in "$weekdays"
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for2-wrong.sh
      Weekday 1 : Mon Tue Wed Thu Fri
 
      3. Don’t specify the list; get it from the positional parameters
 
      If you don’t specify the keyword “in” followed by any list of values in the bash for loop, it will use the positional parameters (i.e the arguments that are passed to the shell script).
 
      $ cat for3.sh
      i=1
      for day
      do
          echo "Weekday $((i++)) : $day"
      done
 
      $ ./for3.sh Mon Tue Wed Thu Fri
      Weekday 1 : Mon
      Weekday 2 : Tue
      Weekday 3 : Wed
      Weekday 4 : Thu
      Weekday 5 : Fri
      Caution: Please be careful if you use this method. You should not include the keyword “in” in the for loop. If you leave the keyword “in” without any values, it will not use the positional parameter as shown below. It will not go inside the loop. i.e for loop will never get executed as shown in the example below.
 
      $ cat for3-wrong.sh
      i=1
      for day in
      do
          echo "Weekday $((i++)) : $day"
      done

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

 
      $ ./for3-wrong.sh Mon Tue Wed Thu Fri
      Note: Refer to our earlier article to understand more about bash positional parameters.
 
      4. Unix command output as list values after “in” keyword
 
      You can use the output of any UNIX / Linux command as list of values to the for loop by enclosing the command in back-ticks ` ` as shown below.
 
      $ cat for4.sh
      i=1
      for username in `awk -F: '{print $1}' /etc/passwd`
      do
          echo "Username $((i++)) : $username"
      done
 
      $ ./for4.sh
      Username 1 : ramesh
      Username 2 : john
      Username 3 : preeti
      Username 4 : jason
      ..
 
      5. Loop through files and directories in a for loop
 
      To loop through files and directories under a specific directory, just cd to that directory, and give * in the for loop as shown below.
      The following example will loop through all the files and directories under your home directory.
 
      $ cat for5.sh
      i=1
      cd ~
      for item in *
      do
          echo "Item $((i++)) : $item"
      done
 
      $ ./for5.sh

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      Item 1 : positional-parameters.sh
      Item 2 : backup.sh
      Item 3 : emp-report.awk
      Item 4 : item-list.sed
      Item 5 : employee.db
      Item 8 : storage
      Item 9 : downloads
      Usage of * in the bash for loop is similar to the file globbing that we use in the linux command line when we use ls command (and other commands).
 
      For example, the following will display all the files and directories under your home directory. This is the concept that is used in the above for5.sh example.
 
      cd ~
      ls *
      The following will display all the *.conf file that begins with either a, b, or, c or d under /etc directory.
 
      $ ls -1 /etc/[abcd]*.conf
      /etc/asound.conf
      /etc/autofs_ldap_auth.conf
      /etc/cas.conf
      /etc/cgconfig.conf
      /etc/cgrules.conf
      /etc/dracut.conf
      The same argument that is used in the ls command above, can be used in a bash for loop, as shown in the example below.
 
      $ cat for5-1.sh
      i=1
      for file in /etc/[abcd]*.conf
      do
          echo "File $((i++)) : $file"
      done
 
      $ ./for5-1.sh
      File 1 : /etc/asound.conf

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      File 2 : /etc/autofs_ldap_auth.conf
      File 3 : /etc/cas.conf
      File 4 : /etc/cgconfig.conf
      File 5 : /etc/cgrules.conf
      File 6 : /etc/dracut.conf
 
      6. Break out of the for loop
 
      You can break out of a for loop using ‘break’ command as shown below.
 
      $ cat for6.sh
      i=1
      for day in Mon Tue Wed Thu Fri
      do
          echo "Weekday $((i++)) : $day"
          if [ $i -eq 3 ]; then
              break;
          fi
      done
 
      $ ./for6.sh
      Weekday 1 : Mon
      Weekday 2 : Tue
 
      7. Continue from the top of the for loop
 
      Under certain conditions, you can ignore the rest of the commands in the for loop, and continue the loop from the top again (for the next value in the list), using the continue command as shown below.
      The following example adds “(WEEKEND)” to Sat and Sun, and “(weekday)” to rest of the days.
 
      $ cat for7.sh
      i=1
      for day in Mon Tue Wed Thu Fri Sat Sun
      do
          echo -n "Day $((i++)) : $day"
          if [ $i -eq 7 -o $i -eq 8 ]; then

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

              echo " (WEEKEND)"
              continue;
          fi
          echo " (weekday)"
      done
 
      $ ./for7.sh
      Day 1 : Mon (weekday)
      Day 2 : Tue (weekday)
      Day 3 : Wed (weekday)
      Day 4 : Thu (weekday)
      Day 5 : Fri (weekday)
      Day 6 : Sat (WEEKEND)
      Day 7 : Sun (WEEKEND)
 
      8. Bash for loop using C program syntax
 
      This example uses the 2nd method of bash for loop, which is similar to the C for loop syntax. The following example generates 5 random number using the bash C-style for loop.
 
      $ cat for8.sh
      for (( i=1; i <= 5; i++ ))
      do
          echo "Random number $i: $RANDOM"
      done
 
      $ ./for8.sh
      Random number 1: 23320
      Random number 2: 5070
      Random number 3: 15202
      Random number 4: 23861
      Random number 5: 23435
 
      9. Infinite Bash for loop
 
      When you don’t provide the start, condition, and increment in the bash C-style for loop, it will become infinite loop. You need to press Ctrl-C to stop the loop.

海姹网(网址:http://www.seacha.com),标签:Linux Shell for循环写法总结, awk,expr

      
      $ cat for9.sh
      i=1;
      for (( ; ; ))
      do
          sleep $i
          echo "Number: $((i++))"
      done
      Like we said above, press Ctrl-C to break out of this bash infinite for loop example.
 
      $ ./for9.sh
      Number: 1
      Number: 2
      Number: 3
 
      10. Using comma in the bash C-style for loop
 
      In the bash c-style loop, apart from increment the value that is used in the condition, you can also increment some other value as shown below.
      In the initialize section, and the increment section of the bash C-style for loop, you can have multiple value by separating with comma as shown below.
      The following for loop is executed a total of 5 times, using the variable i. However the variable j start with 5, and getting increment by 5 every time the loop gets executed.
 
      $ cat for10.sh
      for ((i=1, j=10; i <= 5 ; i++, j=j+5))
      do
          echo "Number $i: $j"
      done
 
      $ ./for10.sh
      Number 1: 10
      Number 2: 15
      Number 3: 20
      Number 4: 25
      Number 5: 30
 
      11. Range of numbers after “in” keyword
 
      You can loop through using range of numbers in the for loop “in” using brace expansion.
      The following example loops through 10 times using the values 1 through 10.
 
      $ cat for11.sh
      for num in {1..10}
      do
          echo "Number: $num"
      done
 
      $ ./for11.sh
      Number: 1
      Number: 2
      Number: 3
      Number: 4
      Number: 5
      ...
 
      12. Range of numbers with increments after “in” keyword
 
      The following example loops through 5 times using the values 1 through 10, with an increment of 2. i.e It starts with 1, and keeps incrementing by 2, until it reaches 10.
 
      $ cat for12.sh
      for num in {1..10..2}
      do
          echo "Number: $num"
      done
 
      $ ./for12.sh
      Number: 1
      Number: 3
      Number: 5
      Number: 7
      Number: 9
 
来源未知。

Bash For Loop Examples for Your Linux Shell Scripting--ref的更多相关文章

  1. Linux Shell Scripting Cookbook 读书笔记 1

    本系列文章为<Linux Shell Scripting Cookbook>的读书笔记,只记录了我觉得工作中有用,而我还不是很熟练的命令 书是很好的书,有许多命令由于我比较熟悉,可能就没有 ...

  2. Bash For Loop Examples

    How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set ...

  3. Linux Shell Scripting Cookbook 读书笔记 7

    ping, du, ps, kill, 收集系统信息 判断网络中哪些主机是活动主机 #!/bin/bash for ip in 10.215.70.{1..255}; do ( ping $ip -c ...

  4. Linux Shell Scripting Cookbook 读书笔记 2

    cat,script,find, xargs, tr, tmp文件,字符串截取,批量文件重命名,固定大小文件,自动化交互 1. cat的用法 压缩连续的空白行 cat -s file 也可以用tr,将 ...

  5. Linux Shell Scripting Tutorial (LSST) v2.0

    http://bash.cyberciti.biz/wiki/index.php?title=Main_Page

  6. Linux Shell Scripting Cookbook 读书笔记 6

    wget,curl, tar, rsync wget ftp://example.com/somefile.img -t 5 -O download.img -o log -t表示重试的次数 -O指定 ...

  7. Linux Shell Scripting Cookbook 读书笔记 5

    sed,awk 1. sed (string editor) 使用-i可以将结果运用于原文件 sed 's/text1/text2/' file > newfile mv newfile fil ...

  8. Linux Shell Scripting Cookbook 读书笔记 4

    正则, grep 1. 正则表达式  正则表达式  描述  示例 ^ 行起始标记  ^hell匹配以hell开头的行 $ 行尾标记  test$匹配以test结尾的行 . 匹配任意一个字符  hell ...

  9. Linux Shell Scripting Cookbook 读书笔记 3

    patch, tree, head ,tail 1. 创建不可修改文件 chattr +i file chattr -i file 移除不可修改属性 2. 能够启动闪存或硬盘的混合ISO isohyb ...

随机推荐

  1. 给自己加油,一定要学会MFC!

    我自己对于没有学会MFC始终耿耿于怀,都什么时代了啊,但是我仍然坚持会去学MFC,因为MFC虽然落后与复杂,但是在Windows平台上仍然是无所不能的(其实Windows平台仍然是唯一可以赚钱的平台, ...

  2. jquery ajax传递数组给php

    写成:var data = {'item[]':item}; $.post(url,data,function(return_data) 写成item:item会导致数据缺失. 更多:http://w ...

  3. Emeditor所有快捷键操作

    新建文本    Ctrl+N         创建一个新的文本文件. 打开         Ctrl+O    打开一个已存在的文件. 保存         Ctrl+S     保存当前文件. 重新 ...

  4. C# word开发

    c# 操作Word总结 在医疗管理系统中为保存患者的体检和治疗记录,方便以后的医生或其他人查看.当把数据保存到数据库中,需要新建很多的字段,而且操作很繁琐,于是想到网页的信息创建到一个word文本中, ...

  5. jQuery append xmlNode 修改 xml 内容

    jQuery append xmlNode 修改 xml 内容 http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/04/29/jqu ...

  6. 关于css样式的看法

    1.通常有两种方式,第一种是直接写在页面标签中,通过属性style,另一种是通过标签选择器赋样式 第一种方式,就是每一个标签都需要写一遍样式,同时没有做到样式和内容的分离,不方便以后的样式替换,主题的 ...

  7. Java笔记(三)……基础语法

    关键字 标识符 在程序中自定义的一些名称 由26个英文字母大小写,数字:0-9,符号:_ $组成 定义合法标识符规则: 数字不可以开头. 不可以使用关键字. Java中严格区分大小写. 注意:在起名字 ...

  8. jquery实现无外边框table

    jquery实现无外边框table 在需要设为无外边框的table上加上class noOutBorder <tableclass="noOutBorder"> < ...

  9. 树形遍历(java)---孩子双亲表示法

    给定一个树形结构,如图: 将它转换为孩子双亲表示法: 以下是JAVA实现://先序遍历 import java.util.ArrayList; public class TreeTraverse{ s ...

  10. POJ1050:To the max

    poj1050:http://poj.org/problem?id=1050 * maximum-subarray 问题的升级版本~ 本题同样是采用DP思想来做,同时有个小技巧处理:就是把二维数组看做 ...