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. html5/css3响应式布局介绍及设计流程

    html5/css3响应式布局介绍 html5/css3响应式布局介绍及设计流程,利用css3的media query媒体查询功能.移动终端一般都是对css3支持比较好的高级浏览器不需要考虑响应式布局 ...

  2. php Static静态关键字

    静态属性与方法可以在不实例化类的情况下调用,直接使用类名::方法名的方式进行调用.静态属性不允许对象使用->操作符调用. class Car { private static $speed =  ...

  3. django查询常用操作符及models和admin的写法

    以Publisher.Author.Book的model为例子 #coding=utf-8 from django.db import models # Create your models here ...

  4. C++有关类的符号总结

    因为我先学习的java,尽管c++与java在类声明与使用上很相似,但是看到c++的源码还是有一些符号不太明白..现在就用一个例子总结一下: #include <iostream> cla ...

  5. xe6+firedac连接sybase

    一.Win7 X64系统安装sybase odbc: 1.  下载对应包至c:\system_odbc(文件夹名自己取,在后面注册表内容需要用到): 2.  将值信息写入到注册表内: Windows ...

  6. 什么是xsi:type ???

    http://www.w3.org/2001/XMLSchema-instance http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.ecli ...

  7. 靓号正则表达式(前后向查找等) 和 apache正则包使用

    一般公司在开发一类对的号码时,会预留一些号码给以后升级的会员使用,比如旺旺靓号,QQ号等,采用正则表达式实现较好,通过规则引擎的后台页面做成实时可配置的也是不错的选择. 一. 一般会有如下的正则需求 ...

  8. QLGame 2d Engine Android端环境搭建(通过jni读取assets目录的文件)

    QLGame 2d Engine win端已经实现了一个动物的动画了,初步的东西已经完成,考虑在Android端也实现这些基本的东西,这样跨平台的引擎也就实现了! 要在Android下编程,首先要实现 ...

  9. 运行 Docker 容器时的安全风险:别丢了你的套接字

    我们都遇到过这种情况:你只是想尝试一段命令行,但安装进程却如同抵押贷款申请那般繁琐.如果不是强制要求完成这么多步骤,你的开发环境会被永远不会再使用的库弄乱.自然, Docker 来了以后,你惊异地发现 ...

  10. 练习生产者与消费者-PYTHON多线程中的条件变量同步-Queue

    以前练习过,但好久不用,手生,概念也生了, 重温一下.. URL: http://www.cnblogs.com/holbrook/tag/%E5%A4%9A%E7%BA%BF%E7%A8%8B/ ~ ...