π 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.