For Loop in Shell Scripting

Many times we need to execute a certain part of our code to be executed repeatedly. Loop is one of the alternative solutions available in the programing Which saves our time as well as improved the coding standards.

A ‘for loop’ is a bash programming language statement that 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 a list of files using for a 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 .. 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

[email protected]:~# for i in 1 2 3 4 5 7 9;do echo “The value of i = “$i; done
The value of i = 1
The value of i = 2
The value of i = 3
The value of i = 4
The value of i = 5
The value of i = 7
The value of i = 9

Printing in the range

[email protected]:~# for i in {1..6};do echo “The value of i = “$i; done
The value of i = 1
The value of i = 2
The value of i = 3
The value of i = 4
The value of i = 5
The value of i = 6

Printing in the range with step

[email protected]:~# for i in {1..6..2};do echo “The value of i = “$i; done
The value of i = 1
The value of i = 3
The value of i = 5

Printing in the range with step in the reverse

[email protected]:~# for i in {6..1..2};do echo “The value of i = “$i; done
The value of i = 6
The value of i = 4
The value of i = 2

Send a Message