shell script for loop example

Mastering Shell Scripts: A For Loop Example

By Jessica Allen
AD

In the realm of scripting, loops are fundamental constructs that enable repetitive tasks to be automated. Shell scripting, a powerful tool for Unix-based systems, also supports loops. Today, we'll explore an essential shell script for loop example that demonstrates the use of the 'for' loop, a staple in scripting languages.

The 'for' loop in shell scripting is particularly useful when you need to execute a block of code for a specified number of times or for each item in a list. It's a versatile tool that can simplify complex tasks and boost your productivity. Let's dive into an example that illustrates its power.

Looping Through a List of Files

One of the most common use cases for a 'for' loop in shell scripting is iterating over a list of files. This can be particularly useful when you need to perform the same operation on multiple files, such as renaming, moving, or processing them in some way.

AD
Linux Shell Guide
Linux Shell Guide
Fun with Control Structures in Shell Scripting - SlideServe
Fun with Control Structures in Shell Scripting - SlideServe
Linux Shell script to display Files and Folders in Specific Directory | ls command in linux #shorts
Linux Shell script to display Files and Folders in Specific Directory | ls command in linux #shorts

Let's consider a scenario where you have a directory containing several text files, and you want to append a timestamp to the name of each file. Here's how you can achieve this using a 'for' loop:

Using a 'for' Loop with a List

The basic syntax for a 'for' loop in shell scripting is as follows:

Bash scripting cheatsheet
Bash scripting cheatsheet
Shell Scripting for Automation (Beginner Guide)
Shell Scripting for Automation (Beginner Guide)
some type of calligraphy written in cursive writing, with the letters below it
some type of calligraphy written in cursive writing, with the letters below it
for variable in list
do
    command
done

In our example, the 'list' will be a list of files in the current directory. We can use the '*' wildcard to match all files in the directory. Here's the script:

#!/bin/bash

for file in *
do
    if [ -f "$file" ]; then
        mv -- "$file" "${file}_$(date +%Y%m%d%H%M%S)"
    fi
done

This script loops through each item in the current directory. If the item is a file (not a directory), it uses the 'mv' command to rename the file by appending a timestamp to its name. The timestamp is generated using the 'date' command in the format 'YYYYMMDDHHMMSS'.

AD

To run this script, save it to a file (e.g., 'loop_example.sh'), make it executable with the command 'chmod +x loop_example.sh', and then run it with './loop_example.sh'.

Mastering bash String Operators and Arrays in UNIX Shells
Mastering bash String Operators and Arrays in UNIX Shells
How to Send Email using Shell Script | Send mails using a Bash Script | Shell Scripting for DevOps
How to Send Email using Shell Script | Send mails using a Bash Script | Shell Scripting for DevOps
Font - shelley script allegro
Font - shelley script allegro
credit to tania.fontanet on ig!!
credit to tania.fontanet on ig!!
a drawing of a seashell with bubbles coming out of it's shell and the word sea written in cursive writing
a drawing of a seashell with bubbles coming out of it's shell and the word sea written in cursive writing
Summer Seashell Font
Summer Seashell Font

Looping Through an Array

In some cases, you might want to loop through a specific list of items rather than all files in a directory. In shell scripting, you can achieve this by using an array. Here's how you can modify our previous example to loop through an array of file names:

#!/bin/bash

files=("file1.txt" "file2.txt" "file3.txt")

for file in "${files[@]}"
do
    if [ -f "$file" ]; then
        mv -- "$file" "${file}_$(date +%Y%m%d%H%M%S)"
    fi
done

In this version of the script, we've defined an array called 'files' containing the names of the files we want to process. The loop then iterates over this array instead of all files in the current directory.

AD

Looping Based on a Condition

Another powerful use case for 'for' loops in shell scripting is looping based on a condition. This can be particularly useful when you need to perform a task until a certain condition is met.

the outline of a seashell on a white background
the outline of a seashell on a white background
a drawing of a shell with a heart on it
a drawing of a shell with a heart on it
the outline of a shell on a pink background
the outline of a shell on a pink background
a white shell on a blue background with the words, `'i am not sure what
a white shell on a blue background with the words, `'i am not sure what
a drawing of a shell with leaves and flowers around it
a drawing of a shell with leaves and flowers around it
Shelly Font
Shelly Font
Shell Yeah svg...
Shell Yeah svg...
An Introduction to Shell in Linux - SoftPrayog
An Introduction to Shell in Linux - SoftPrayog
Seashell By Ugla Studio
Seashell By Ugla Studio
Seashell Font Free Download
Seashell Font Free Download
the letters and numbers are made out of seashells
the letters and numbers are made out of seashells
an open book with drawings of seashells and other things in it's pages
an open book with drawings of seashells and other things in it's pages
a black and white drawing of a shell
a black and white drawing of a shell
Justine Bloom: Travel - Prayer - Writing (Brand Mark)
Justine Bloom: Travel - Prayer - Writing (Brand Mark)

Let's consider a scenario where you want to keep guessing a random number until the user guesses it correctly. Here's how you can achieve this using a 'for' loop with a condition:

Guessing a Random Number

In this example, we'll use a 'for' loop to repeatedly prompt the user to guess a number until they guess the correct number. Here's the script:

AD
#!/bin/bash

number_to_guess=$((RANDOM % 10 + 1))
attempts=0

for guess in
do
    read -p "Guess a number between 1 and 10: " guess
    ((attempts++))
    if [ "$guess" -eq "$number_to_guess" ]; then
        echo "Congratulations! You guessed the number in $attempts attempts."
        break
    elif [ "$guess" -lt "$number_to_guess" ]; then
        echo "Too low! Try again."
    else
        echo "Too high! Try again."
    fi
done

In this script, we first generate a random number between 1 and 10 using the 'RANDOM' variable and the modulo operator. We then use a 'for' loop to repeatedly prompt the user to guess the number. The loop continues until the user guesses the correct number, at which point the 'break' statement is used to exit the loop.

In the vast world of shell scripting, loops are essential tools that can help you automate repetitive tasks and simplify complex workflows. The 'for' loop, in particular, is a versatile construct that can be used in a wide range of scenarios. Whether you're looping through a list of files or looping based on a condition, the 'for' loop is a powerful tool that can help you boost your productivity and streamline your workflow.

As you continue to explore the world of shell scripting, we encourage you to experiment with loops and other constructs to see what you can achieve. With practice, you'll find that shell scripting is a powerful and flexible tool that can help you automate a wide range of tasks.

AD