for
for
The for loop in Unix-like operating systems is a fundamental control structure in shell scripting. It allows you to iterate over a list of items or the output of a command, performing a set of commands for each item. This can be highly useful for automating repetitive tasks.
Basic Syntax
for variable in list
do
commands
donevariable: The name of the variable that will take on each value in the list, one at a time.
list: A list of items, which can be hardcoded values, the output of a command, or a range.
commands: The commands to execute for each item in the list.
Examples
Iterating Over a List of Values
for color in red green blue
do
echo "Color: $color"
doneOutput:
Color: red
Color: green
Color: blueIterating Over a Range of Numbers
for i in {1..5}
do
echo "Number: $i"
doneOutput:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5Iterating Over the Output of a Command
for file in $(ls *.txt)
do
echo "Processing $file"
doneOutput:
Processing file1.txt
Processing file2.txt
Processing file3.txtUsing C-style Syntax
Some shells, like bash, support a C-style syntax for for loops:
for ((i=1; i<=5; i++))
do
echo "Number: $i"
doneOutput:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5Practical Use Cases
Processing Files in a Directory
for file in /path/to/directory/*
do
echo "Found file: $file"
# Add commands to process the file here
doneBacking Up Files
for file in *.conf
do
cp "$file" "/backup/directory/$file.bak"
echo "Backed up $file to /backup/directory/$file.bak"
doneRenaming Files
for file in *.jpg
do
mv "$file" "${file%.jpg}.jpeg"
echo "Renamed $file to ${file%.jpg}.jpeg"
doneChecking Services Status
services=("nginx" "mysql" "php-fpm")
for service in "${services[@]}"
do
systemctl status $service
doneNested Loops
You can nest for loops to handle more complex scenarios:
for dir in /path/to/parent/*
do
echo "Directory: $dir"
for file in "$dir"/*
do
echo " File: $file"
done
doneConclusion
The for loop is an essential tool in shell scripting, providing a way to automate repetitive tasks by iterating over lists of items or command outputs. By mastering the for loop, you can significantly enhance your ability to write efficient and effective shell scripts.
help
Last updated