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 .. 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)
![](http://figs.cyberciti.biz/warning-40px.png)
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的更多相关文章
- 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 ...
- Linux Bash Script loop
Linux Bash Script loop shell 编程之流程控制 for 循环.while 循环和 until 循环 for var in item1 item2 ... itemN do c ...
- 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 ...
- 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 ...
- CodeForces-757B Bash's Big Day
题目链接 https://vjudge.net/problem/CodeForces-757B 题目 Description Bash has set out on a journey to beco ...
- 【codeforces 757B】 Bash's Big Day
time limit per test2 seconds memory limit per test512 megabytes inputstandard input outputstandard o ...
- linux shell except tcl login ssh Automatic interaction
/*************************************************************************************** * linux she ...
- centos 7安装部署docker
1.centos 7 在windows下通过vm虚拟机安装centos 7: VMware-workstation-full-10.0.3-1895310 centos 7 2.要求 操作系统的内核版 ...
- 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 ...
随机推荐
- Shell符号展开
字符 展开 * 这个 “*” 字符意味着匹配文件名中的任意字符 shell 把 “*” 展开成了另外的东西 ,在 echo 命令被执行前. ~家目录 算术表达式展开 算术表达式展开使用这种格式: $( ...
- 网站开发常用jQuery插件总结(八)标签编辑插件Tagit
一.Tagit插件功能 提高网站交互性,增加用户体验.至于其它的功能,还真没有.用一个input text就可以替换了它.但是text没有输入提示功能,而tagit拥有这个功能.官方示例如下图: 将关 ...
- javaScript & jquery完美判断图片是否加载完毕
好久没写东西了,正好最近因为工作需要,写了一个瀑布流异步加载的程序. 今天就不谈瀑布流,来谈一下关于load的问题. ----------------------------------------- ...
- linux系统文件的颜色代表的意思
1.蓝色代表目录 2.绿色代表可执行文件 3.红色代表可压缩文件 4.白色代表其他文件 5.浅蓝色代表链接文件 6.黄色代码设备 7.红色闪烁表示链接的文件有问题
- 根据WSDL生成代理类方式(2)
运行开发人员工具提示 输入命令行svcutil http://localhost:8080/Test/TestClassPort?wsdl
- 移动应用产品开发-android开发(二)
这段时间实在太忙了,也没什么精力来写博客,还是没养成写博客的习惯,还是得记载下来,不然时间久了就忘记了. 早上一大早就来公司了,趁还早,拟定今天的工作内容和计划后,赶紧记载点东西. 最近做androi ...
- Gson把json串转换成java实体对象
Gson把json串转换成java实体对象的方法如下: 1.首先导入Gson的jar包,网上可以下载. java实体对象如下: public class Model { private double ...
- CAS单点登录配置[1]:准备工作
关于CAS是什么这里就不在赘述,网友将它比喻成旅游景点的套票,买了一个套票就可以观看所有景点,不需要一个景点买一次票...我们重点介绍CAS单点登录的配置. 工具/原料 1.配置好JDK环境,否则不方 ...
- [转贴]从零开始学C++之STL(二):实现一个简单容器模板类Vec(模仿VC6.0 中 vector 的实现、vector 的容量capacity 增长问题)
首先,vector 在VC 2008 中的实现比较复杂,虽然vector 的声明跟VC6.0 是一致的,如下: C++ Code 1 2 template < class _Ty, cl ...
- 如何在C++中使用WebService
gsoap主页 http://sourceforge.net/projects/gsoap2 使用gsoap生成所需的WebService 下载后的gsoap包为:(点击到我的资源中下载) 将他解 ...