KandZ – Tuts

We like to help…!

Linux CLI 64 🐧 for loop in shell scripts

a - for loop in shell scripts intro
for loop is used to iterate over a sequence of items or values
This type of loop is very useful for executing the same command or set of commands multiple times with different inputs.
syntax:

for variable in item1 item2 ... itemN
do
Commands to be executed for each iteration
done

varialbe is a placeholder that takes on each value from the item list, one at a time.
items are values or items (like numbers, strings, file names) that the loop will iterate over.
you can also use C-style syntax:

for (( initialization; condition; increment ))
do
Commands to be executed for each iteration
done

Initialization → This expression is executed only once before the loop starts. It usually initializes one or more variables.
Condition → This expression is evaluated at the start of every iteration. If it evaluates to true (non-zero), the loop body executes; if false (zero), the loop ends.
Increment → This expression is executed after each iteration of the loop body, typically used to update the loop variable(s).

b - for loop examples
Simple loop
Simple loop using seq command
Simple loop using C-style syntax
Simple loop using {start..end} syntax
Loop through all .sh files in the current directory
Nested loops
Loop through each line of the output from 'ls' command

Leave a Reply