Bash: Unleashing the Power of For Loops with Real Time Use Cases

In the following post, you will unleash the power of “For Loops” with Real-Time Use Cases.

Syntax of for loop:
for ((initialization; condition; update)); do

# Commands to be executed in each iteration

done

Here is the simple bash script that uses a “for” loops to print numbers from 1 to 10 along with Real-Time application use cases:

# Bash script that uses a “for” loop to print numbers from 1 to 10

#!/bin/bash

echo "Printing numbers from 1 to 10:"

# For loop to iterate from 1 to 10

for ((i=1; i<=10; i++)); do

echo "$i"

done
Now, let’s break down the specific components in the script:

((i=1; i<=10; i++)):

This is the initialization, condition, and update section of the loop.

i=1 initializes the loop counter i to the value 1.

i<=10 is the loop condition. The loop will continue as long as i is less than or equal to 10.

i++ is the update statement. It increments the value of i by 1 after each iteration.

do:

Marks the beginning of the loop body. The commands inside the loop will be executed in each iteration.

echo “$i”:

Prints the current value of i in each iteration of the loop.

done:

Marks the end of the loop.

The entire loop can be read as follows: “For each value of i from 1 to 10 (inclusive), print the value of i.”

Real-time application use cases:
1. Generating a sequence of file names
  • Generating a sequence of file names and creating empty files with those names.
#!/bin/bash

for ((i=1; i<=10; i++)); do

touch "file_$i.txt"

done

echo "Created 10 files: file_1.txt, file_2.txt, ..., file_10.txt"

2. Running a command for each iteration
  • Running a command for each iteration of the loop (represented by “Processing item $i” in the example).
#!/bin/bash

for ((i=1; i<=10; i++)); do

echo "Processing item $i"

# Add your real-time application command here

done
3. Creating directories based on the loop variable
  • Creating directories based on the loop variable.
#!/bin/bash

for ((i=1; i<=10; i++)); do

mkdir "directory_$i"

done

echo "Created 10 directories: directory_1, directory_2, ..., directory_10"

4. System Resource Monitoring
  • Checks CPU usage for 10 iterations.
#!/bin/bash

echo "Checking CPU usage for 10 iterations:"

for i in {1..10}; do

echo "Iteration $i - CPU Usage: $(top -bn1 | awk '/%Cpu/{print $2}')%"

sleep 1

done

Now, let’s break down the specific components in the script:

for i in {1..10}; do:

  • This line initiates a for loop in Bash. It uses the range expression {1..10}, which generates a sequence of values from 1 to 10 (inclusive).
  • In each iteration of the loop, the variable i takes on a different value from the specified range.

echo “Iteration $i – CPU Usage: $(top -bn1 | awk ‘/%Cpu/{print $2}’)%”:

  • The echo statement prints a message to the standard output.
  • The message includes the current iteration number ($i), the text “CPU Usage:”, and the result of a command substitution.
  • Starts top in Batch mode, which could be useful for sending output from top to other programs or to a file. In this mode, top will not accept input and runs until the iterations limit you’ve set with the `-n’ command-line option or until killed.
  • “awk” script enclosed in single quotes. It specifies a pattern-action pair.
  • / %Cpu/ is a regular expression pattern that looks for lines containing the string “%Cpu”.
  • {print $2} is the action associated with the pattern. It instructs awk to print the second field of the matched line.

5. Database Operations
  • Simulates inserting 10 records into a database.
#!/bin/bash

echo "Inserting 10 records into a database using a for loop:"

for i in {1..10}; do

# Assuming a database insert command, replace with actual command

echo "INSERT INTO table_name (column1, column2) VALUES ('$i', 'data_$i');"

done
6. Network Testing
  • Pings a server 10 times.
#!/bin/bash

echo "Pinging a server 10 times using a for loop:"

server="example.com"

for i in {1..10}; do

ping -c 1 $server

done
7. Running Commands on Remote Servers
  • Executes a command on a remote server 10 times.
#!/bin/bash

echo "Executing a command on a remote server 10 times:"

remote_server="user@remote_server"

command_to_run="echo 'Hello, World!'"

for i in {1..10}; do

ssh $remote_server "$command_to_run"

done

echo "Script execution completed."

Each use case involves iterating over a range of values for various real-time scenarios, showcasing the versatility of Bash scripting in automating repetitive tasks.

Feel free to modify the script according to your specific use case or replace the real-time application examples with your own commands or actions.

How do you feel about this post? Drop your comments below..