0
0
Bash Scriptingscripting~5 mins

for loop (list-based) in Bash Scripting

Choose your learning style9 modes available
Introduction
A for loop helps you repeat actions for each item in a list. It saves time and avoids writing the same code many times.
You want to print each file name in a folder.
You need to run a command on several servers one by one.
You want to process a list of user names to create accounts.
You want to check each word in a list for spelling.
You want to automate tasks that repeat for many items.
Syntax
Bash Scripting
for item in list
 do
   commands using "$item"
 done
The list can be words, file names, or any items separated by spaces.
Use double quotes around "$item" to handle items with spaces.
Examples
Prints each color name from the list.
Bash Scripting
for color in red green blue
 do
   echo "$color"
 done
Prints all files ending with .txt in the current folder.
Bash Scripting
for file in *.txt
 do
   echo "File: $file"
 done
Handles names with spaces by quoting each item.
Bash Scripting
for name in "Alice" "Bob Smith" "Charlie"
 do
   echo "Hello, $name!"
 done
Sample Program
This script loops over a list of fruits and prints a message for each one.
Bash Scripting
#!/bin/bash

# List of fruits
fruits="apple banana cherry"

echo "Fruits before loop: $fruits"

for fruit in "$fruits"
 do
   echo "I like $fruit"
 done
OutputSuccess
Important Notes
Time complexity is O(n), where n is the number of items in the list.
Space complexity is low, just storing the list and current item.
Common mistake: forgetting to quote "$item" can cause errors if items have spaces.
Use for loops when you have a fixed list of items. Use while loops for conditions or unknown counts.
Summary
A for loop repeats commands for each item in a list.
Always quote variables like "$item" to handle spaces safely.
For loops are simple and great for running commands on many items.