Bash For Loop Examples

How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using for statement? How do I use three-parameter for loop control expression?

A ‘for loop‘ is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script.

For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

for loop syntax

Numeric ranges for syntax is as follows:

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

OR

for VARIABLE in file1 file2 file3
do
    command1 on $VARIABLE
    command2
    commandN
done

OR

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
    command1 on $OUTPUT
    command2 on $OUTPUT
    commandN
done

Examples

This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop:

#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Sometimes you may need to set a step value (allowing one to count by two‘s or to count backwards for instance). Latest bash version 3.0+ has inbuilt support for setting up ranges:

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

Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:

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

Sample outputs:

Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

The seq command (outdated)

WARNING! The seq command print a sequence of numbers and it is here due to historical reasons. The following examples is only recommend for older bash version. All users (bash v3.x+) are recommended to use the above syntax.

The seq command can be used as follows. A representative example in seq is as follows:

There is no good reason to use an external command such as seq to count and increment numbers in the for loop, hence it is recommend that you avoid using seq. The builtin command are fast.

Three-expression bash for loops syntax

This type of for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

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

A representative three-expression example in bash as follows:

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

Sample output:

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

How do I use for as infinite loops?

Infinite for loop can be created with empty expressions, such as:

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

Conditional exit with break

You can do early exit with break statement inside the for loop. You can exit from within a FOR, WHILE or UNTIL loop using break. General break statement inside the for loop:

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

Following shell script will go though all files stored in /etc directory. The for loop will be abandon when /etc/resolv.conf file found.

#!/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

Early continuation with continue statement

To resume the next iteration of the enclosing FOR, WHILE or UNTIL loop use continue statement.

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

This script make backup of all file names specified on command line. If .bak file exists, it will skip the cp command.

#!/bin/bash
FILES="[email protected]"
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
时间: 2024-12-26 18:41:44

Bash For Loop Examples的相关文章

Bash String Manipulation Examples – Length, Substring, Find and Replace--reference

In bash shell, when you use a dollar sign followed by a variable name, shell expands the variable with its value. This feature of shell is called parameter expansion. But parameter expansion has numerous other forms which allow you to expand a parame

[Bash Programming] loop

CONDITION: bash命令: 用命令的执行状态结果: 成功:true 失败:flase 成功或失败的意义:取决于用到的命令: 单分支: if CONDITION; then if-true fi 双分支: if CONDITION; then if-true else if-false fi 多分支: if CONDITION1; then if-true elif CONDITION2; then if-ture elif CONDITION3; then if-ture ... es

bash - array

http://www.artificialworlds.net/blog/2012/10/17/bash-associative-array-examples/ Bash associative array examples

linux shell except tcl login ssh Automatic interaction

/*************************************************************************************** * linux shell except tcl login ssh Automatic interaction * 声明: * 本程序是使用except自动登入远程目标机,并且执行commands文件中的命令给定的命令, * 可以对多个目标机进行测试,目标机的IP保存在shell的数组中,目前只支持相同的账户和密码.

Shell脚本初级练习篇

Shell脚本初级练习篇 脚本1 作用:创建10个1M的文件 [[email protected] script]# cat make_file.sh  #!/bin/bash # for i in $(seq 1 10);do     dd if=/dev/zero of=/data/test/test"${i}" bs=1M count=1 done 脚本2 作用:移走/data/test目录下大于100K的普通文件到/tmp目录下 [[email protected] scrip

Map Class Example

Here's a quick look at how to use the Scala Map class, with a colllection of Map class examples. The immutable Map class is in scope by default, so you can create an immutable map without an import, like this: val states = Map("AL" -> "A

亲热接触Redis-第一天

引言 nosql,大规模分布式缓存遍天下.Internet的时代在中国由其走得前沿,这一切归功于我国特色的电商. 因此nosql.大数据技术在中国应用的比国外还要前沿. 从这一章開始我们将開始进入到真正的SOA.PAAS.SAAS.互联网的领域,因此每一篇我都会添加一小段业务的基础知识,让大家在学习技术的同一时候也能够了解一些业务,这边的业务不是指的business logic不是让大家去做业务人员,而是为大家带来IDEA,"没有做不到仅仅有想不到",阿里支付宝为什么发了...不是技术

Install Docker on Mac OS X(转)

Install Docker on Mac OS X You can install Docker using Boot2Docker to run docker commands at your command-line. Choose this installation if you are familiar with the command-line or plan to contribute to the Docker project on GitHub. Alternatively,

PYTHON-进阶-ITERTOOLS模块

PYTHON-进阶-ITERTOOLS模块小结 这货很强大, 必须掌握 文档 链接 pymotw 链接 基本是基于文档的翻译和补充,相当于翻译了 itertools用于高效循环的迭代函数集合 组成 总体,整体了解 无限迭代器 迭代器 参数 结果 例子 count() start, [step] start, start+step, start+2*step, ... count(10) --> 10 11 12 13 14 ... cycle() p p0, p1, ... plast, p0,