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. jQuery如何检查某个元素在网页上是否存在

    $("ID")获取的永远是对象,即使网页上没有此元素.因此当要用jQuery检查某个元素在网页上是否存在时,不能使用以下代码: if($("#ID")){ // ...

  2. ubuntu 下安装软件,卸载,查看已经安装的软件

    参考网址:http://wiki.ubuntu.org.cn/UbuntuSkills 一般的安装程序用三种: .deb 和.rpm 这两种安装文件 .bundle 这是二进制的安装文件 而 tar. ...

  3. sql的连接查询方式

    1 SQL join 用于根据两个或多个表中的列之间的关系,从这些表中查询数据. Join 和 Key 有时为了得到完整的结果,我们需要从两个或更多的表中获取结果.我们就需要执行 join. 数据库中 ...

  4. php url字符转义操作

    遇到一段代码,从数据库里读出来带 \ 字符 需要转义成中文~ 用到url_decode(); //$info 为刚从数据库中读取的二维数组 foreach($info as $key1 => & ...

  5. odoo 清除所有运行数据

    测试odoo,如果需要一个干净的db.经常需要清除掉所有业务数据.做如下操作,较为方便 1:建立一个服务器动作,动作的python代码入下. 然后新建一个菜单,菜单动作关联到 这个动作.需要清空db, ...

  6. C#中获得汉字的首拼音(加强版)

    /// <summary> /// 汉字拼音首字母列表 /// 包含了20901个汉字,收录的字符的Unicode编码范围为19968至40869 /// </summary> ...

  7. jquery直接获取html页面元素

    大家都会用$('div')来获取div并对其进行一些操作,今天用到一个函数发现$('div')与getElementBy系列函数得到的对象并不一样. 然后去查了下,发现$('div')得到的是一个数组 ...

  8. iOS 改变UILabel部分颜色

    //协议 UILabel *xieLabel = [[UILabel alloc] init]; xieLabel.textColor = TextGrayColor; xieLabel.font = ...

  9. CAGradientLayer的一些属性解析-b

    CAGradientLayer的一些属性解析 iOS中Layer的坐标系统: 效果: - (void)viewDidLoad { [super viewDidLoad]; CAGradientLaye ...

  10. ReactEurope Conf 参会感想

    React 带来的革命性创新是前端世界过去几年最激动人心的变化.自从接触 React 以来,我深信 React 会改变客户端开发者(包括前端.iOS 和 Android)的开发体验.这次在巴黎举办的  ...