Skip to content
Log In Sign Up info@muvcloud.com

The Basic Form

#!/usr/bin/env bash
for service in nginx mariadb redis; do
    echo "Checking $service"
    systemctl is-active "$service"
done

The variable service takes each word in turn, and the lines between do and done run once per word. At the prompt, the same loop fits on one line:

for service in nginx mariadb redis; do systemctl is-active "$service"; done

Loop Over a Range of Numbers

#!/usr/bin/env bash
for i in {1..10}; do
    echo "Run $i"
done

Brace ranges also take a step and keep leading zeros:

  • {0..100..10}: 0, 10, 20, and so on to 100.
  • {01..12}: 01, 02, up to 12, useful for month numbers.
  • {10..1}: counts down.

Braces cannot use variables: {1..$n} does not expand. Use the C-style loop for that.

C-Style Loop

#!/usr/bin/env bash
count="${1:-5}"
for (( i = 1; i <= count; i++ )); do
    echo "Attempt $i of $count"
done

Inside (( )) Bash does arithmetic, so variables do not need a $ and the comparison <= is numeric.

Loop Over Files

#!/usr/bin/env bash
shopt -s nullglob
for file in /var/log/nginx/*.log; do
    echo "$file: $(wc -l < "$file") lines"
done
  • Use a glob, not ls: for f in $(ls) breaks on file names with spaces. The glob passes each name intact.
  • Quote the variable: always write "$file".
  • nullglob: without it, a pattern that matches nothing is passed on literally as the text /var/log/nginx/*.log.

To process files in all subfolders, enable shopt -s globstar and use **/*.log.

Read a File Line by Line

For lines of text, use while read rather than for, which splits on every space:

#!/usr/bin/env bash
while IFS= read -r domain; do
    [[ -z "$domain" ]] && continue
    echo "Checking $domain"
    getent hosts "$domain"
done < domains.txt

IFS= keeps spaces at the start and end of each line, and -r keeps backslashes as they are. The [[ … ]] test is Bash's own form of the older [ … ] command: it does not split variables into words, so it is safer.

Loop Over Script Arguments

#!/usr/bin/env bash
for path in "$@"; do
    du -sh "$path"
done

"$@" keeps each argument whole, even with spaces. For more on arguments, see how to write a Bash script.

break and continue

#!/usr/bin/env bash
shopt -s nullglob
for file in /var/backups/*.tar.gz; do
    if [[ ! -s "$file" ]]; then
        echo "Skipping empty $file"
        continue
    fi
    if ! tar -tzf "$file" > /dev/null; then
        echo "Damaged archive: $file"
        break
    fi
    echo "OK: $file"
done

continue skips to the next item; break leaves the loop. In nested loops, continue 2 and break 2 act on the outer loop.

Common Mistakes

  • Missing do or done: Bash reports a syntax error near the end of the file. Check with bash -n script.sh.
  • Quoting the whole list: for x in "a b c" runs once, with the full string.
  • Changing files while looping: test with echo first, then replace it with the real command.

Combine loops with if statements to act only on items that match a condition. A loop that reads a list of folders from a variable such as BACKUP_DIRS gets that value from the environment; see how to set environment variables in Linux.

Updated:

Linux VPS with Full Root Access

MUVCloud cloud servers run on KVM with Enterprise NVMe SSD storage and full root access, in Turkey, the Netherlands, and the USA.

Cloud VPS Plans Starting at2.99 $/mo Cheap Linux VPS

No Limits on Service or Support

You are not on your own as your projects grow. Our support engineers are ready 24/7, on several channels, whenever you need them.

Support specialist
  • 100% customer satisfaction goal
  • Our own hardware
  • 24/7 ticket and email support
  • 4 countries with locations