Panduan Lengkap Perintah for i in di Linux: Dari Dasar Sampai Pro

Looping adalah salah satu skill fundamental yang wajib dikuasai sysadmin atau developer. Di Linux bash scripting, perintah for i in adalah workhorse buat otomasi tugas-tugas repetitif. Artikel ini bakal ngebahas semua variasi dan use case for loop dari yang paling basic sampe teknik advanced.

Apa Itu for i in Loop?

Sebelum masuk ke contoh, penting buat paham konsep dasarnya:

  • Iterasi: Loop bakal jalanin command berulang kali buat setiap item di list
  • Variable $i: Bisa diganti nama apa aja, ini cuma placeholder buat current item
  • Word splitting: Bash bakal split berdasarkan whitespace secara default
  • Flexible: Bisa iterate file, angka, string, atau output command lain

Sintaks dasarnya simple tapi powerful:

for variable in list; do
    # commands here
done

1. Loop Melalui List String (Dasar)

Cara paling basic dan sering dipake buat iterate beberapa item yang udah ditentuin.

Contoh Sederhana

for i in apple banana orange; do
    echo "Buah: $i"
done

Output:

Buah: apple
Buah: banana
Buah: orange

Variabel Nama Bebas

Gak harus pake i, bisa pake nama yang deskriptif:

for server in web1 web2 web3; do
    ping -c 1 "$server"
done

Tips: Selalu quote variable kaya "$server" biar gak kena masalah kalo ada spasi di nama.

2. Loop Melalui File dan Direktori

Ini yang paling sering dipake sysadmin buat batch processing file.

Loop Semua File di Direktori

for file in *.txt; do
    echo "Processing: $file"
    wc -l "$file"
done

Loop dengan Path Lengkap

for i in /var/log/*.log; do
    echo "File: $i"
    ls -lh "$i"
done

Handle Filename dengan Spasi

Kalo ada kemungkinan spasi di nama file, tambahin IFS atau quote:

# Method 1: IFS (Internal Field Separator)
IFS=$'\n'
for file in $(ls *.pdf); do
    echo "File: $file"
done
unset IFS

# Method 2: Read array (Lebih aman)
for file in *.pdf; do
    [ -f "$file" ] && echo "Processing: $file"
done

Recursive Loop (Semua Subdirektori)

for i in $(find /home/user -name "*.conf" -type f); do
    echo "Backup: $i"
    cp "$i" "$i.bak"
done

3. Loop dengan Range Angka (C-style)

Buat iterate angka berurutan, pake syntax {start..end} atau seq.

Range Sederhana

for i in {1..5}; do
    echo "Iterasi ke-$i"
done

Dengan Step/Interval

# Bilangan genap 2 sampe 10
for i in {2..10..2}; do
    echo "Angka: $i"
done

# Countdown
for i in {10..1..-1}; do
    echo "Hitung mundur: $i"
    sleep 1
done

Alternatif dengan seq

Kalo butuh padding angka nol atau format khusus:

# Dengan leading zero (01, 02, 03...)
for i in $(seq -w 1 10); do
    mkdir "folder-$i"
done

# Step 5
for i in $(seq 0 5 100); do
    echo "Progress: $i%"
done

4. Loop dari Output Command

Bisa juga iterate hasil output command lain, ini super powerful buat dynamic list.

Baca dari File

for user in $(cat users.txt); do
    echo "Creating user: $user"
    sudo useradd -m "$user"
done

Baca dari Command Lain

# Restart semua service yang failed
for service in $(systemctl --failed --plain | grep "failed" | awk '{print $1}'); do
    echo "Restarting $service..."
    sudo systemctl restart "$service"
done

Loop dari ls (Hati-hati!)

# Jangan begini kalo ada spasi:
# for i in $(ls)  ❌ Bahaya

# Begini yang benar:
for i in *; do
    [ -f "$i" ] && echo "File: $i"
done

5. Array Looping (Advanced)

Buat data yang lebih kompleks, pake bash array.

Array Satu Dimensi

# Definisikan array
servers=("web1.local" "web2.local" "db1.local" "db2.local")

for i in "${servers[@]}"; do
    echo "Checking $i..."
    ssh "$i" "uptime"
done

Array dengan Index

fruits=("Apple" "Banana" "Orange")

for i in "${!fruits[@]}"; do
    echo "Index $i: ${fruits[$i]}"
done

Associative Array (Key-Value)

declare -A users
users=([john]="admin" [jane]="developer" [bob]="viewer")

for i in "${!users[@]}"; do
    echo "User: $i, Role: ${users[$i]}"
done

6. Nested Loop (Loop di Dalam Loop)

Buat kombinasi atau matrix processing.

Kombinasi Sederhana

for i in 1 2 3; do
    for j in a b c; do
        echo "Kombinasi: $i$j"
    done
done

Praktis: Multi-Server Multi-Command

servers=("web1" "web2")
commands=("uptime" "df -h" "free -m")

for server in "${servers[@]}"; do
    echo "=== $server ==="
    for cmd in "${commands[@]}"; do
        echo "Running: $cmd"
        ssh "$server" "$cmd"
    done
done

7. Break dan Continue (Control Flow)

Kadang perlu skip iterasi atau stop loop lebih awal.

Skip Iterasi dengan continue

for i in {1..10}; do
    # Skip bilangan genap
    [ $((i % 2)) -eq 0 ] && continue
    echo "Bilangan ganjil: $i"
done

Stop Loop dengan break

for i in $(cat servers.txt); do
    if ! ping -c 1 "$i" &> /dev/null; then
        echo "Server $i down! Stop processing."
        break
    fi
    echo "Deploying to $i..."
done

Break Level (Nested Loop)

for i in {1..3}; do
    for j in {a..c}; do
        if [ "$i" -eq 2 ] && [ "$j" = "b" ]; then
            break 2  # Break semua loop, bukan cuma inner
        fi
        echo "$i$j"
    done
done

8. Real-World Use Cases

Contoh praktis yang sering dipake di production.

Batch Rename File

count=1
for file in *.jpg; do
    newname="vacation_$(printf "%03d" $count).jpg"
    mv "$file" "$newname"
    ((count++))
done

Backup Multiple Database

databases=("db_prod" "db_staging" "db_logs")
date_stamp=$(date +%Y%m%d)

for db in "${databases[@]}"; do
    echo "Backing up $db..."
    mysqldump -u root -p"$DB_PASS" "$db" > "${db}_${date_stamp}.sql"
    gzip "${db}_${date_stamp}.sql"
done

Parallel Processing (Background Job)

for i in {1..10}; do
    (
        echo "Start job $i at $(date)"
        sleep $((RANDOM % 5))
        echo "Finish job $i at $(date)"
    ) &
done

wait  # Tunggu semua background job selesai
echo "All jobs completed!"

Check Multiple Port

servers=("google.com" "github.com" "gitlab.com")
ports=(80 443 22)

for server in "${servers[@]}"; do
    for port in "${ports[@]}"; do
        timeout 2 bash -c "echo >/dev/tcp/$server/$port" 2>/dev/null &&
            echo "$server:$port OPEN" ||
            echo "$server:$port CLOSED"
    done
done

9. One-Liner For Loop (Command Line)

Buat quick task tanpa bikin script file.

Format One-Liner

# Syntax
for i in list; do command; done

# Contoh: Hapus log lama
for i in $(find /var/log -name "*.log" -mtime +7); do rm -f "$i"; done

# Contoh: Convert image
for i in *.png; do convert "$i" "${i%.png}.jpg"; done

Multiple Commands dengan && dan ||

for i in *.tar.gz; do tar -xzf "$i" && rm "$i" || echo "Failed: $i"; done

10. Best Practices dan Common Pitfalls

DoDon’t
Selalu quote variable "$i"for i in $(ls) tanpa quote
Pake IFS=$'\n' kalo handle file dengan spasiLoop file tanpa handle spasi
Check file exists [ -f "$i" ] sebelum processLangsung process tanpa verify
Pake set -e di script buat error handlingSilent fail tanpa notice
Gunakan array kalo datanya kompleksPanjangin list string manual

Template Script Aman

#!/bin/bash
set -euo pipefail  # Strict mode

# IFS aman untuk handle spasi
IFS=$'\n\t'

for file in *.txt; do
    # Check file exists
    [ -f "$file" ] || continue
    
    # Process dengan error handling
    if ! process_file "$file"; then
        echo "Error processing $file" >&2
        continue
    fi
done

Kesimpulan

Perintah for i in di Linux itu simple tapi powerful banget. Dari yang cuma iterate list string sampe complex nested loops dengan parallel processing, semua bisa dihandle.

Key takeaways:

  • Basic: for i in item1 item2 item3 buat list statis
  • File: for i in *.ext buat batch file processing
  • Range: for i in {1..10} buat angka berurutan
  • Dynamic: for i in $(command) buat list dari output lain
  • Array: for i in "${array[@]}" buat data kompleks

Leave a Reply

Your email address will not be published. Required fields are marked *