Bash Loops - Learn While and For Loops | Online Free DevTools by Hexmos

Master Bash scripting with our guide on while and for loops. Learn to iterate and control your scripts effectively. Free online tool for developers.

Bash Loops Tutorial

Understanding Bash Loops

Bash scripting provides powerful looping constructs to automate repetitive tasks. This guide covers the essential while and for loops, crucial for any developer working with the command line. Mastering these loops will significantly enhance your ability to write efficient and dynamic shell scripts.

27.1. While Loops in Bash

A while loop in Bash is used to execute a block of commands repeatedly as long as a specified condition remains true. This is ideal for scenarios where the number of iterations is not predetermined.

  • The loop runs as long as the given condition is true.
  • Syntax: bash while [ condition ]; do commands; done

27.1.1. While Loop Example

Here's an example demonstrating how to print all the directories containing files with the .c extension. This utilizes the find command piped into a while loop to process each file found.

find . -name *.c | { while read -r filename; do dirname "$filename"; done; } | sort | uniq

In this script, dirname is used to extract the directory name from the full file path.

27.2. For Loops in Bash

The for loop in Bash is used to iterate over a list of items (like filenames, numbers, or strings) or execute commands a preset number of times. It's perfect for processing collections of data.

  • The loop iterates over a list of values or a preset number of times.
  • Syntax: bash for <variable name> in <a list of items>; do <some command> $<<variable name>; done;

27.2.1. For Loop Example

This example shows how to copy all text files (.txt) from a ./code/ directory to a backup directory /home/code/backup/.

for file in ./code/*.txt; do cp "$file" /home/code/backup/; done

This loop iterates through each file matching the pattern ./code/*.txt and executes the cp command for each one.

Further Learning Resources