For loop in shell scripts
A for loop is used to repeat the same set of code.
If we want our script to repeat the same set of code say around 10 or 100 times, we can use a for loop.
For Loops in Linux Shell Scripting
Syntax1:
for { variable name } in { list } do { code to execute } done
Syntax2:
for($start_num; Range; $increment) do { code to execute } done
Example1: for1.sh
for (( i = 0 ; i <= 5; i++ )) do echo "Welcome $i times" done
Result:
./for1.sh Welcome 0 times Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times
In the above example the initial value of " i = 0 ".
The loop executed until the value of " i " reached 5.
Example2: for2.sh
# Get the value from the user echo " Enter a value for the variable x:" read x # For loop for (( a = $x; a <= 10; a++ )) do echo "The value of x is $a now" done
Result:
./for2.sh Enter a value for the variable x: 7 The value of x is 7 now The value of x is 8 now The value of x is 9 now The value of x is 10 now
Nested for loop
You can nest the for loop.
To understand the nesting of for loop try the following shell script.
Example: nested-for.sh
for (( i = 1; i <= 5; i++ )) # 1st loop do for (( j = 1 ; j <= 5; j++ )) # 2nd loop do echo "The value of i is $i " echo "The value of j is $j " done echo -e "\n" ## print the new line done
Result:
./nested-for.sh The value of i is 1 The value of j is 1 The value of i is 1 The value of j is 2 The value of i is 1 The value of j is 3 ...... .....
Related posts:
- Shell Scripting Introduction
- Shell Syntax
- Shell - Strings
- Shell - Variables
- Shell - User Intraction
- First Shell Script
- Shell - Arithmetics
- Shell - Case Statement
- Shell - Command Line Arguments
- Shell - For Loop
- Shell - While Loops
- Shell - IF Statements
- Shell - Input Output Redirections
- Shell - Pipes and Filters
- Shell - Process Management
Your IP address1 is: 172.18.0.2
Tutorials
Latest Updates
Follow us
- Tech-Tutorials twitter.com/techcuriosity