Conditions and loops
if with [[ ]] and (( )), case patterns, for over words, a range or a C-style counter, and while.
Runs in Zerethon IDE · Bash 5.2
Official Bash documentation ↗
main.sh
for n in {1..5}; do
if (( n % 2 == 0 )); then
echo "$n even"
elif [[ $n -eq 5 ]]; then
echo "$n last"
else
echo "$n odd"
fi
done
i=3
while (( i > 0 )); do
(( i-- ))
[[ $i -eq 1 ]] && continue
echo "i = $i"
done
for (( k = 0; k < 2; k++ )); do
echo "k = $k"
done
file="photo.png"
case "$file" in
*.png | *.jpg) echo "image" ;;
*.txt) echo "text" ;;
*) echo "other" ;;
esac
[[ -f main.sh ]] && echo "main.sh exists"
[[ "abc" < "abd" ]] && echo "abc sorts first"
Output
1 odd 2 even 3 odd 4 even 5 last i = 2 i = 0 k = 0 k = 1 image main.sh exists abc sorts first
(( ... ))compares numbers with<,==,%; inside[[ ... ]]numbers use-eq,-lt,-gt, and==/<compare text.- Spaces are required inside the brackets:
[[ $n -eq 5 ]], not[[$n -eq 5]]. - File tests:
-ffile exists,-dfolder exists,-ztext is empty,-ntext is not empty. cmd && otherrunsotheronly ifcmdsucceeded;cmd || otheronly if it failed.