Bash For Loop Examples for Your Linux Shell Scripting--ref

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.

      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.

 
      $ 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,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,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

      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"

      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

 
      $ ./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

      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

      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

              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.

      
      $ 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
 
来源未知。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


系ubuntu 下面打开终端输入:sudo apt-get install sendmail一般就安装完成噶啦跟住进入 /etc/mail/目录输入:m4 sendmail.mc &gt; sendmail.cf意思系跟住.mc文件 生成 sendmial.cf文件输入呢个命令:ps aux | g
依家我有1个软件goagent目录(大家懂得) 放在/home/gateman/Programs/ 下 1. proxy.py 入面有1个 proxy.py 文件 放在/home/gateman/Programs/goagent/local/ 入面 2.breakwall.sh 我在 proxy.p
其实我想讲的是 cp -L关于-L参数的解释:-L, --dereference always follow symbolic links in SOURCE意思是如果复制目标是1个软链接,则复制链接的目标 不是链接本身做个例子: 例如 ~/tmp/fo1 入面有1个c.txt 文件 和 指向他的软
原地址:http://www.rjgc.net/control/content/content.php?nid=4418 1、将文件checkout到本地目录svn checkout path(path是服务器上的目录)例如:svn checkout svn://192.168.1.1/pro/do
chroot,即 change root directory (更改 root 目录)。在 linux 系统中,系统默认的目录结构都是以 `/`,即是以根 (root) 开始的。而在使用 chroot 之后,系统的目录结构将以指定的位置作为 `/` 位置。实例:用live CD ubuntu假设你的
简单解析下, stdin就是标准输入, stdout就是标准。举个例子, 在当前我要打包1个文件夹 /var/log/ 到当前目录下,并用zip压缩,那么我们可以分步执行#tar -cvf log.tar /var/log/#zip -r log.tar.zip log.tar#rm -rf log
转自:http://man.ddvip.com/linux/Mandrakelinuxref/process-priority.html系统中运行的每个进程都有一个优先级(亦称“nice 值”),其范围从 -20 (最高优先级)到 19 (最低优先级)。默认情况下,进程的优先级是 0 (“基本”调度
str=&quot;/home/gateman&quot; if [ ${str:0:1} = &quot;/&quot; ]; then echo &quot;yes&#39;fi ${str:0:1} 中0表示从第几个字符开始,1表示截取多长
转自:http://kwokchivu.blog.51cto.com/1128937/694347 在RedHat系统下用usermod 命令可把某用户添加进多个附属组,默认情况下,一次性添加多个附属组可用以下方式来添加: usermod -G 附属组1,附属组2,...,附属组X 用户名 但在添加
有个文件 test.txt 内容如下:bash-3.00$ cat test.txt user user user_hiuser #注:呢行系空行T JGATEMANGATTTTTEMANGABBEMANAAABbash-3.00$下面介绍下常用的通配符 配合grep 命令:1. &quot;.&q
linux系统为每1个文件都分配有i索引节点(inode),系统根据呢d节点从磁盘找出数据。 一般来讲,每1个文件名(包含全路径)实际上都链接住1个i索引节点。inode实际上系乜咧? 其实可以算系1个指向磁盘具体位置(柱面,扇区之类)的指针, 系统分析某个文件的inode,得出磁盘柱面,扇区等数据
grep 可以立即为筛选, 一般的用法系 grep + 要查询的字段 + 文件(或者内容 例如| 传递既内容)1.grep + 要查询的字段 + 文件gateman@GPC:~/shell/SQL_GSI$ grep OID a.sqlWHERE OID=@BuildNOWHERE OID INWH
原文转自:http://www.ibm.com/developerworks/cn/linux/l-cn-vimcolumn/index.html开始之前人类大脑对文字的处理是平面式的,所以我们浏览文章、查找资料或者重构代码,要么是横向读,要么是纵向读,要么使用搜索功能,将文字作为一个平面整体。而在
PS:偶很喜欢用scp这个命令来传输数据。scp命令跟cp命令类似,只不过cp命令是在同一台机器上用的,scp是在两台机器上复制传输数据的命令。scp实质相当于利用SSH协议来传输数据的cp命令。 用法举例: 1、复制远程服务器的文件到本地: scp -P888 root@120.18.50.33:
打开终端,进入/bin/ls 一下会见到 bash sh 呢两个文件。其实距地系两个唔同既shell 解析器。如果在脚本a.sh 开头写入#!/bin/sh那么执行./a.sh 时候 就相当于 sh a.sh同理 开头写入#!/bin/bash执行./a.sh 时候 就相当于 bash a.sh如果
find查找文件的时候排除某个或几个文件或目录转自:http://www.cnblogs.com/starspace/archive/2008/10/20/1315380.html比如要在/usr/sam目录下查找不在dir1子目录之内的所有文件find /usr/sam -path &quot;/
假设有变量 var=http://www.google.com/test.htm一 # 号截取,删除左边字符,保留右边字符。echo ${var#*//}其中 var 是变量名,# 号是运算符,*// 表示从左边开始删除第一个 // 号及左边的所有字符即删除 http://结果是 :www.goog
转自: http://edyfox.codecarver.org/html/_vimrc_for_beginners.htmlVIM 中可供用户定制的选项非常非常多,作为初学者,我们没有必要了解这么多东西。下面,滇狐简单列出了一些最常用的配置项,大家可以根据自己的需要将这些内容添加到自己的 .vim
转自:http://www.einit.com/user1/11/archives/2006/3603.htmlUnix/Linux下一般想让某个程序在后台运行,很多都是使用 &amp; 在程序结尾来让程序自动运行。比如我们要运行mysql在后台: /usr/local/mysql/bin/mysq
首先, mount是类unix系统, 挂载设备到1个文件夹的操作命令, 注意系设备阿正常来讲,mount 是不能挂在文件夹到文件夹的。例如, 在我的~/tmp/ 目录中有两个文件夹fo1 fo2其中fo1 中有3个文件a.txt b.txt c.txt fo2 有4个 e.txt d.txt e.t