- 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.
or loop syntax
Numeric ranges for syntax is as follows:
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
for VARIABLE in file1 file2 file3
do
command1 on $VARIABLE
command2
commandN
done
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
command1 on $OUTPUT
command2 on $OUTPUT
commandN
done
#!/bin/bash
for i in 1 2 3 4 5
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 {1..5}
do
echo "Welcome $i times"
done
#!/bin/bash
echo "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 times Welcome 2 times Welcome 4 times Welcome 6 times Welcome 8 times Welcome 10 times
No comments:
Post a Comment