Advertisement
Learning Bash scripting might feel like staring at a brick wall—plain, intimidating, and hard to get through. But it doesn't have to be that way. If you’ve ever wanted to automate repetitive tasks, manage files, or process data on Linux or macOS, knowing how to use a Bash for loop is one of the most practical starting points. It’s not about memorizing commands or syntax but understanding how this basic loop works and how it fits into actual use cases. Once that clicks, things start to fall into place. It won’t take hours, and you won’t need a computer science degree. Just a few clear examples and a bit of practice.
A for loop in Bash is a control flow structure that repeats commands for each item in a list. Think of it like a checklist: it looks at each item and performs the same action until it finishes the list. The real strength of a for loop is in its simplicity and flexibility. You can loop through a sequence of numbers, a list of filenames, output from a command, or anything else that can be expanded into a list.
There are two common forms of for loops in Bash. The first is the "list" form, where you explicitly define each item:
for items in one, two, three
do
echo $item
done
The second is the C-style loop, familiar if you’ve seen languages like C or JavaScript:
for ((i = 1; i <= 5; i++))
do
echo "Number $i"
done
Both forms have their place, and choosing between them depends on the problem you're solving. The first is great when working with files or arguments, while the second works well for counting.
Once you've mastered the syntax, the next step is to see what you can actually do with it. Bash for loops is often used in automation. They repeat tasks like renaming files, converting formats, searching through text, or backing up data.
Let's say you have a directory full of .txt files and want to rename them all to .bak. A simple script using a for loop does the job:
for file in *.txt
do
mv "$file" "${file%.txt}.bak"
done
This script loops over every .txt file in the directory and renames it by removing .txt and replacing it with .bak. The ${file%.txt} part strips the .txt extension. You don’t need to open each file manually—this loop handles it.
Another example is converting images from one format to another with a tool like convert from ImageMagick. Suppose you have .png files you want as .jpg:
for img in *.png
do
convert "$img" "${img%.png}.jpg"
done
The loop doesn't care how many files there are. Whether it’s five or five hundred, the same script will work.
You can also use Bash for loops to monitor system status. For instance, if you want to ping a few servers and log whether they're online:
for server in server1.com server2.com server3.com
do
ping -c 1 $server &> /dev/null
if [ $? -eq 0 ]; then
echo "$server is online"
else
echo "$server is offline"
fi
done
This loop runs a single ping to each server, suppresses the output, and checks the result. If the return code is zero, the server is reachable. If not, it's likely down. It’s quick, clean, and doesn’t require complicated logic.
One overlooked use of the for loop in Bash is working with command output. Let’s say you want to loop through all logged-in users:
for user in $(who | awk '{print $1}')
do
echo "User: $user"
done
Here, the who command lists all logged-in users, and awk extracts just the usernames. The for loop then prints each one. It’s fast and avoids manual steps.
Be cautious, though. The loop might break if your command output contains spaces or special characters. Quoting and escaping help, but switching to a while-read loop is more reliable if things get tricky. That said, the basic loop works well in many day-to-day cases.
Another way to use this is to process lines in a file. Say you have a list of email addresses in a file called emails.txt, and you want to send a simple message to each (mocked with echo here):
for email in $(cat emails.txt)
do
echo "Sending message to $email"
done
This assumes each email address is on a separate line and has no spaces. If that’s not the case, a more careful loop is better. But for quick jobs, this works.
Bash scripting isn’t hard, but it does have quirks. One of the most common mistakes is not quoting variables. If a filename has a space, unquoted variables will break the loop:
for file in *
do
echo $file
done
If there's a file named My File.txt, it gets split into two words. Fix it by quoting the variable:
for file in *
do
echo "$file"
done
Another thing to watch out for is modifying a list while looping through it. For example, you might run into errors if you delete files inside a for loop that's looping over *. Make sure your loop is built with that in mind, or use a snapshot list stored in a variable at the start:
files=(*)
for file in "${files[@]}"
do
rm "$file"
done
This way, the list doesn’t change while you’re looping.
And don’t forget about break and continue. These let you exit a loop early or skip a step:
for i in {1..10}
do
if [ $i -eq 3 ]; then
continue
fi
if [ $i -eq 7 ]; then
break
fi
echo "Number: $i"
done
This skips the number 3 and stops the loop at 7.
The Bash for loop is a simple tool with a wide reach. It saves time, reduces mistakes, and handles repetitive work quietly and reliably. You don't need to know every command or option—just a handful of clear patterns you can adjust depending on your work. Whether renaming files, looping through numbers, processing lists, or running checks across systems, the for loop can do the job. It's not flashy, but it's effective and one of the easiest ways to start feeling in control of the command line. Once you start using it, you'll wonder how you worked without it.
Advertisement
AWS' generative AI platform combines scalability, integration, and security to solve business challenges across industries
How the apt-get command in Linux works with real examples. This guide covers syntax, common commands, and best practices using the Linux package manager
How can Google’s Gemma 3 run on a single TPU or GPU? Discover its features, speed, efficiency and impact on AI scalability.
What is Auto-GPT and how is it different from ChatGPT? Learn how Auto-GPT works, what sets it apart, and why it matters for the future of AI automation
Discover three new serverless inference providers—Hyperbolic, Nebius AI Studio, and Novita—each offering flexible, efficient, and scalable serverless AI deployment options tailored for modern machine learning workflows
How using Xet on the Hub simplifies code and data collaboration. Learn how this tool improves workflows with reliable data versioning and shared access
Microsoft’s new AI model Muse revolutionizes video game creation by generating gameplay and visuals, empowering developers like never before
How the world’s first AI-powered restaurant in California is changing how meals are ordered, cooked, and served—with robotics, automation, and zero human error
A clear and practical guide for open source developers to understand how the EU AI Act affects their work, responsibilities, and future projects
Ready to run powerful AI models locally while ensuring safety and transparency? Discover Gemma 2 2B’s efficient architecture, ShieldGemma’s moderation capabilities, and Gemma Scope’s interpretability tools
Explore the top 10 large language models on Hugging Face, from LLaMA 2 to Mixtral, built for real-world tasks. Compare performance, size, and use cases across top open-source LLMs
Multimodal models combine text, images, and audio into a shared representation, enabling AI to understand complex tasks like image captioning and alignment with more accuracy and flexibility