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      .. 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
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 {..}
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 {....}
do
echo "Welcome $i times"
done

Sample outputs:

Bash version 4.0.()-release...
Welcome times
Welcome times
Welcome times
Welcome times
Welcome times
Welcome 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=; c<=; c++ ))
do
echo "Welcome $c times"
done

Sample output:

Welcome  times
Welcome times
Welcome times
Welcome times
Welcome 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
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
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="$@"
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

Bash For Loop Examples的更多相关文章

  1. 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, ano ...

  2. Linux Bash Script loop

    Linux Bash Script loop shell 编程之流程控制 for 循环.while 循环和 until 循环 for var in item1 item2 ... itemN do c ...

  3. 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 wi ...

  4. Codeforces 757B. Bash's Big Day GCD

    B. Bash's Big Day time limit per test:2 seconds memory limit per test:512 megabytes input:standard i ...

  5. CodeForces-757B Bash's Big Day

    题目链接 https://vjudge.net/problem/CodeForces-757B 题目 Description Bash has set out on a journey to beco ...

  6. 【codeforces 757B】 Bash's Big Day

    time limit per test2 seconds memory limit per test512 megabytes inputstandard input outputstandard o ...

  7. linux shell except tcl login ssh Automatic interaction

    /*************************************************************************************** * linux she ...

  8. centos 7安装部署docker

    1.centos 7 在windows下通过vm虚拟机安装centos 7: VMware-workstation-full-10.0.3-1895310 centos 7 2.要求 操作系统的内核版 ...

  9. Install Docker on Mac OS X(转)

    Install Docker on Mac OS X You can install Docker using Boot2Docker to run docker commands at your c ...

随机推荐

  1. 使用Map辅助拼装树状结构,消除递归调用

    目前菜单或其他树状结构在数据库中的存储,多数是以一个parentid作为关联字段,以一维形式存储.使用时全部查询出来,然后在内存中拼装成树状结构.现在主要涉及的是拼装方法的问题. 一般可以进行 递归调 ...

  2. stream_context_create解决file_get_contents超时处理

    stream_context_create作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置.代理服务器.请求方式.头信息设置的 ...

  3. networkRequest

    void TPHttp::applyResource(){    QJsonObject json;    json.insert("ProductCode","MoVd ...

  4. 列表页url参数格式分析【求指教】

    运营对列表页url制定静态化模式,与区区观点相悖.遂请大家指教点解. 动态参数包含6个,分别是: 1认证(有机),2品类(水果),3地区(丰台),4状态(众筹中),5排序(评分),6分页 使用状态非常 ...

  5. swift swizzle

    SWIZZLE 由 王巍 (@ONEVCAT) 发布于 2015/09/30 Swizzle 是 Objective-C 运行时的黑魔法之一.我们可以通过 Swizzle 的手段,在运行时对某些方法的 ...

  6. myeclipse使用SVN团队开发

    很多时候我们做项目都是已一个团队一起开发,所以我们可以选择SVN开发工具. 一:了解SVN的使用流程: 1).有一个服务端,他可以在上面添加一个项目,添加成员 2).myeclipse需要安装svn的 ...

  7. EntityFramework动态组合多排序字段

    前言:在使用EF当中,肯定会遇到动态查询的需求,建立一个公共调用的动态组合表达式查询也是必不可少的,以下是建立动态组合多排序字段做个记录,供以后调用 1.建立一个结构,用于多个排序字段组合,这个结构体 ...

  8. Being a Hero

    zoj3241:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3241 题意:一个国家的地图是一张n个点m条边的有向图.你保 ...

  9. PYTHON连MS SQL示例

    先要设置WINDOWS的系统DSN的.然后才可以哟. import pyodbc conxn = pyodbc.connect('DSN=BBB; DATABASE=Northwind;UID=AAA ...

  10. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@Scope、ProxyMode

    一. Spring的bean默认是单例的 But sometimes you may find yourself working with a mutable class that does main ...