Preface :
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 :
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 :
Sometimes you may need to set a step value (allowing one to count by two’s or to count backwards for instance). It can be done easily with seq command. A representative example in bash as follows :
Latest bash version 3.0+ has inbuilt support for setting up ranges :
Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax :
上面執行結果 :
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).
A representative three-expression example in bash as follows :
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
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 :
執行結果 :
Early continuation with continue statement :
To resume the next iteration of the enclosing FOR, WHILE or UNTIL loop use continue statement.
執行結果 :
Supplement
* nixCraft - Bash For Loop Examples
沒有留言:
張貼留言