Bash For Loop Examples
来源:互联网 发布:知乎 华清远见骗局 编辑:程序博客网 时间:2024/06/11 20:13
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 .. Ndocommand1command2commandNdone
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/bashfor i in 1 2 3 4 5do 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/bashfor 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/bashecho "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 timesWelcome 2 timesWelcome 4 timesWelcome 6 timesWelcome 8 timesWelcome 10 times
The seq command (outdated)
The seq command can be used as follows. A representative example in seq is as follows:
#!/bin/bashfor i in $(seq 1 2 20)do echo "Welcome $i times"done
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 ))docommand1command2command3done
A representative three-expression example in bash as follows:
#!/bin/bashfor (( c=1; c<=5; c++ ))doecho "Welcome $c times..."done
Sample output:
Welcome 1 timesWelcome 2 timesWelcome 3 timesWelcome 4 timesWelcome 5 times
How do I use for as infinite loops?
Infinite for loop can be created with empty expressions, such as:
#!/bin/bashfor (( ; ; ))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 5do statements1 #Executed for all values of ''I'', up to a disaster-condition if any. statements2 if (disaster-condition) thenbreak #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/bashfor file in /etc/*doif [ "${file}" == "/etc/resolv.conf" ]thencountNameservers=$(grep -c nameserver /etc/resolv.conf)echo "Total ${countNameservers} nameservers defined in ${file}"breakfidone
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 5do statements1 #Executed for all values of ''I'', up to a disaster-condition if any. statements2 if (condition) thencontinue #Go to next iteration of I in the loop and skip statements3 fi statements3done
This script make backup of all file names specified on command line. If .bak file exists, it will skip the cp command.
#!/bin/bashFILES="$@"for f in $FILESdo # if .bak backup file exists, read next fileif [ -f ${f}.bak ]thenecho "Skiping $f file..."continue # read next file and skip cp commandfi # we are hear means no backup file exists, just use cp command to copy file/bin/cp $f $f.bakdone
Recommended readings:
- See all sample for loop shell script in our bash shell directory.
- man bash
- help for
- help {
- help break
- help continue
Updated for accuracy!
- Bash For Loop Examples
- Bash For Loop Examples
- 12 Bash For Loop Examples for Your Linux Shell Scripting
- 12 Bash For Loop Examples for Your Linux Shell Scripting
- Keeping You in the Loop – Bash For, While, Until Loop Examples
- bash Cookbook: Solutions and Examples for bash Users
- Loop Invariant Proof examples
- bash脚本运行错误-Bad for loop variable(ubuntu)
- bash脚本运行错误-Bad for loop variable(ubuntu)
- bash Cookbook, 2nd Edition Solutions and Examples for bash Users pdf
- Shell Script While Loop Examples
- bash-If Statement Examples
- Useful Bash examples
- Bash While Loop Example
- 5 Bash Case Statement Examples
- 5 Bash Case Statement Examples
- 5 Bash Case Statement Examples
- [Happy BASH] BASH的loop学习笔记
- 【连载】【FPGA黑金开发板】Verilog HDL那些事儿--串口模块(十一)
- 【连载】【FPGA黑金开发板】Verilog HDL那些事儿--串口模块(十一)
- 逐步设置vim C/C++语法高亮显示和自动缩进
- Eclipse中关联Android源代码的方法
- Mysql日期和时间函数
- Bash For Loop Examples
- Mkey 3G开发培训(一)
- .NET批量大数据插入性能分析及比较(6.使用表值参数)
- error LNK2019 unresolved external symbol __imp__*** 的原因之一
- poj 2808题校门外的树(java)
- poj1388——Ugly Numbers
- 【连载】【FPGA黑金开发板】Verilog HDL那些事儿--低级建模 仿顺序操作(十二)
- linux gb2312 to utf-8
- Shell Script While Loop Examples