Skip to main content

πŸ”„ Shell Loops

Loops let you repeat actions in your script. This guide introduces the basic shell script loops.


The for Loop​

The for loop repeats commands for each item in a list.

Basic Syntax​

for VARIABLE in ITEM1 ITEM2 ITEM3; do
ACTIONS
done

Example​

for file in "/sdcard/test1.txt" "/sdcard/test2.txt"; do
if exist "$file"; then
ui_print "$file exists"
fi
done

This checks if each file exists and prints a message if it does.

tip

The variable (file) holds the current item each time the loop runs.


The while Loop​

The while loop runs as long as a condition is trueβ€”like waiting for something.

Basic Syntax​

while CONDITION; do
ACTIONS
done

Example​

count=1
while is_less $count 4; do
ui_print "Count: $count"
count=$((count + 1))
done

This Prints Numbers from 1 to 3.


The until Loop​

The until loop runs until a condition becomes trueβ€”the opposite of while.

Basic Syntax​

until CONDITION; do
ACTIONS
done

Example​

attempts=0
until is_equal $attempts 2; do
ui_print "Attempt: $attempts"
attempts=$((attempts + 1))
done

This prints attempts until reaching 2.