Skip to content

Instantly share code, notes, and snippets.

@lucasmezencio
Created November 12, 2024 11:19
Show Gist options
  • Save lucasmezencio/0970af9a40436e99288274b83c1351f8 to your computer and use it in GitHub Desktop.
Save lucasmezencio/0970af9a40436e99288274b83c1351f8 to your computer and use it in GitHub Desktop.
Bash Scripting Loops Basics
# Bash for loop
for i in /etc/*; do
echo "${i}"
done
# Same as above (alternate syntax)
# also works with other loop structures
for i in /etc/*
do
echo "${i}"
done
# Bash while loop
# Incrementing the value
i=1
while [[ ${i} -lt 4 ]]; do
echo "Number ${i}"
((i++))
done
# Decrementing the value
i=3
while [[ ${i} -gt 0 ]]; do
echo "Number ${i}"
((i--))
done
# Bash while True loop
while true; do
# TODO
done
# Shorthand (alternate syntax)
while :; do
# TODO
done
# Break statement
for number in $(seq 1 3); do
if [[ ${number} == 2 ]]; then
# Skip entire rest of
# the loop or break out
# the loop
break;
fi
# This will only print "1"
echo "${number}"
done
# C-like for loop
for ((i = o; i < 100; i++)); do
echo "${i}"
done
# Same as above (alternate syntax)
# also works with other loop structures
for ((i = o; i < 100; i++))
do
echo "${i}"
done
# Continue statement
# Seq command can be used to generate ranges
for number in $(seq 1 3); do
if [[ ${number} == 2 ]]; then
continue;
fi
echo "${number}"
done
# For loop ranges
for i in {1..10}; do
echo "Number: ${i}"
done
# With step size
# => {START..STOP..STEP}
for i in {5..50..5}; do
echo "Number: ${i}"
done
# Reading files
# Using pipes
cat file.txt | while read line
do
echo "${line}"
done
# Using input redirection
while read line; do
echo "${line}"
done < "/path/to/file.txt"
# Until or do loop
# Incrementing
count=0
until [ ${count} -gt 10 ]; do
echo "${count}"
((count++))
done
# Decrementing
count=10
until [ ${count} -eq 0 ]; do
echo "${count}"
((count--))
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment