FUNDAMENTALS A Complete Guide for Beginners
The Bash for loop is more than just a tool. It is a gateway to efficient scripting and streamlined automation. Its simplicity, which seems contradictory to its potential, offers scriptwriters a robust mechanism for streamlining operations. This article will go through some of the common bash scripts where for loop is used.
10 Practical Bash βforβ Loop Examples
The for loop in Bash is a fundamental control structure used for iterating over a list of items. It allows you to execute a sequence of commands repeatedly for each item in the list. It can be used to create patterns, create mathematical sequences, managing files etc. This article will explore 10 practical examples demonstrating the versatility of Bash for loop.
1. Chessboard Pattern Generation
The uses of nested for loops in Bash offer insight into advanced looping techniques for generating complex patterns or iterating through multidimensional data structures. In the following script, a chessboard pattern was created using nested for loop:
#!/bin/bash
#Outer for loop
for (( a = 1; a <= 8; a++ ))
do
#Inner for loop
for (( b = 1 ; b <= 8; b++ ))
do
sum=$(( $a + $b))
temp=$(( $sum % 2))
#setting colors of the chessboard using odd and even number logic
if [ $temp -eq 0 ];
then
echo -e -n "\033[47mΒ "
else
echo -e -n "\033[40mΒ "
fi
done
#printing a new line
echo
done
echo
Here, the outer loop iterates over the rows of the chessboard, while the inner loop iterates over the columns. The script calculates the sum of the row and column numbers within each iteration. It then checks if the sum is even or odd by finding the remainder when divided by 2. Based on the parity of the sum, it alternates between printing white and black squares using ASCII color codes. Finally, after each row is processed, the script moves to the next row of the chessboard.
The chessboard pattern is displayed in the terminal.
2. Isosceles Triangle Pattern Generation
Using the versatility of the for loop in Bash, a pattern like isosceles triangle or pyramid-like pattern can be created. The following script employs two nested for loops to construct a triangular shape using asterisks *
.Β Here is the script to do so:
#!/bin/bash
for p in 1 2 3 4 5 6 7 8 9 10
do
for q in $(seqΒ -10 -$p)
do
echo -nΒ ' '
done
for r in $(seq 1 $p)
do
echoΒ -nΒ "* "
done
echo
done
This Bash script consists of two nested for loops. The outer loop iterates through numbers from 1 to 10, representing the rows of the triangle. Inside this loop, there are two inner loops. The first inner loop generates spaces before each row, with the number of spaces decreasing as the row number increases. The second inner loop prints asterisks, forming the triangular pattern, with the number of asterisks increasing as the row number increases.
Here, the script displays a formatted multiplication table in the terminal.
3. Multiplication Table (5Γ10) Creation
The functionality of the for loop can be demonstrated by creating a concise multiplication table. This script creates a structured tabular multiplication table using a C style for loop and the printf
command. Execute the bash script below to create a multiplication table of dimension 5 by 10:
#!/bin/bash
echo "Multiplication Table:"
# Print header
echo -e "Β | \c"
for ((i=1; i<=10; i++)); do
printf "%-4s" "$i"
done
echo
# Print separator
echo "-------------------------------------------"
# Print table
for ((i=1; i<=5; i++)); do
echo -n "$i | "
for ((j=1; j<=10; j++)); do
product=$((i * j))
printf "%-4s" "$product"
done
echo
done
This Bash script generates a multiplication table from 1 to 5, each row containing multiples up to 10. It begins by displaying a header with numbers from 1 to 10. After printing a separator line, it enters a loop to generate the table. Within this loop, for each row number, it calculates and prints the product of that number with numbers ranging from 1 to 10. The script utilizes nested loops to iterate through the rows and columns.
The script displays a formatted multiplication table in the terminal.
4. Prime Number Generation
The seq
command in Bash is a utility used to generate sequences of numbers. It allows users to specify starting and ending values, along with an optional increment or decrement step. Execute this Bash script to print all prime numbers in a specific range using the seq
Β command and nested “for” loop:
#!/bin/bash
for num in $(seq 2 50); do
prime=true
for i in $(seq 2 $(($num / 2))); do
if [ $(($num % $i)) -eq 0 ]; then
prime=false
break
fi
done
if $prime; then
echo $num
fi
done
This Bash script generates prime numbers from 2 to 50 using nested loops. It begins by iterating through numbers from 2 to 50, considering each as a potential prime candidate. Within the outer loop, an inner loop tests divisibility from 2 up to half of the number’s value. If the number is not divisible by any integer within this range, it’s marked as prime. The script then checks the prime status and prints the number if it’s determined to be prime.
The script echoes all prime numbers from 1 to 50 in the terminal.
5. Palindrome Checking
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. In other words, it remains unchanged when its characters are reversed. Checking for palindromes is a common task in programming. The following bash script checks if a given number is palindrome using the for loop and conditional statement:
#!/bin/bash
echo "Enter a number: "
read num
reverse=0
temp=$num
for (( ; num > 0; )); do
remainder=$((num % 10))
reverse=$((reverse * 10 + remainder))
num=$((num / 10))
done
if [ $temp -eq $reverse ]; then
echo "Palindrome"
else
echo "Not a palindrome"
fi
This Bash script prompts the user to input a number and reads the input using the read
command. It then initializes variables to store the reversed number and the original input. The script uses a for loop to reverse the digits of the number by repeatedly finding the remainder when divided by 10 and updating the reversed number variable.
After the loop, it compares the reversed number with the original input to determine if the number is a palindrome. Finally, it prints either “Palindrome” or “Not a palindrome” based on the comparison result.
Here the 1st input is a palindrome. And the 2nd one is not palindrome.
6. Fibonacci Calculation
Fibonacci numbers are a series where each number is the sum of the two preceding ones, typically starting with 0 and 1. The Fibonacci sequence is widely used in various mathematical and computational contexts. This Bash script takes a number as input and calculates the corresponding Fibonacci number using a for loop and a user-defined function:
#!/bin/bash
# Function to calculate Fibonacci number using a for loop
fibonacci() {
n=$1
a=0
b=1
if (( n == 0 )); then
echo "0"
elif (( n == 1 )); then
echo "1"
else
for (( i = 2; i <= n; i++ )); do
fib=$((a + b))
a=$b
b=$fib
done
echo "$fib"
fi
}
# Main script starts here
read -p "Enter the number to calculate Fibonacci: " num
# Call the function and print the Fibonacci number
result=$(fibonacci $num)
echo "The Fibonacci number for $num is: $result"
This Bash script calculates the Fibonacci number for a given input. It defines a function fibonacci that iteratively computes the Fibonacci sequence up to the input number. The function initializes variables a and b as the first two Fibonacci numbers. It then uses a for loop to calculate subsequent Fibonacci numbers using the formula where each number is the sum of the two preceding numbers. Finally, it displays the Fibonacci number corresponding to the input.
The script echoes the 51st number of the Fibonacci sequence in the terminal.
7. Factorial Calculation
Factorial is a mathematical operation that calculates the product of all positive integers up to a given number. It is denoted by the symbol !
. The seq
command in Bash is used to generate sequences of numbers. It allows users to specify starting and ending values, along with an optional increment or decrement step. Execute the following Bash script to calculate the factorial of a given number using the seq
command within a “for” loop:
#!/bin/bash
read -p "Enter a number: " num
fact=1
for i in $(seq 1 $num); do
fact=$((fact * i))
done
echo "Factorial of $num is: $fact"
This Bash script calculates the factorial of a given number provided by the user. It prompts the user to enter a number using the read
command and stores it in the variable num
. Then, it initializes the variable fact
to 1, which will store the factorial value. Using a for loop, it iterates from 1 to the input number and multiplies each number to calculate the factorial. Finally, it displays the factorial of the input number.
Here, the script echoes the factorial of 15 in the terminal.
8. Sorting Number
Sorting arrays is a fundamental task in programming to arrange elements in a specific order. Common sorting algorithms include bubble sort, insertion sort, quicksort, etc. In this Bash script, a simple bubble sort algorithm is utilized to arrange an array of integers in ascending order. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process continues until it sorts the entire array.
Here is the script to implement this algorithm using nested for loop and conditional statements:
#!/bin/bash
# Declare an array of integers
numbers=(5 2 8 1 9 3)
# Perform a simple bubble sort
for ((i=0; i<${#numbers[@]}; i++))
do
for ((j=0; j<${#numbers[@]}-i-1; j++))
do
if [ ${numbers[$j]} -gt ${numbers[$((j+1))]} ]; then
temp=${numbers[$j]}
numbers[$j]=${numbers[$((j+1))]}
numbers[$((j+1))]=$temp
fi
done
done
# Print the sorted array
echo "Sorted array:"
echo "${numbers[@]}"
This Bash script sorts an array of integers. First, it declares an array named numbers
containing unsorted integers. The script then iterates through the array using nested for loops, comparing adjacent elements and swapping them if they are in the wrong order. The process continues until it sorts the entire array. Finally, it prints the sorted array to the console.
Here, the script uses bubble sort to sort 6 elements of the array.
9. Password Generator
In the digital age, where cybersecurity is paramount, the need for robust password-generation methods is undeniable. Passwords serve as the first line of defense against unauthorized access to sensitive information. While creating strong passwords manually can be challenging, Bash scripting offers a practical solution. By combining character sets, numerical values, and special symbols, the following Bash script can generate secure passwords tailored to user specifications:
#!/bin/bash
# Define character sets
lowercase="abcdefghijklmnopqrstuvwxyz"
uppercase="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers="0123456789"
symbols="!@#$%^&*()_+-=[]{};':|\",<.>/?\`"
# Take input for password length
read -p "Enter the length of the password: " length
# Initialize password variable
password=""
# Concatenate all character sets
all_chars="$lowercase$uppercase$numbers$symbols"
# Generate password using for loop
for (( i = 0; i < length; i++ )); do
char="${all_chars:RANDOM%${#all_chars}:1}"
password+="$char"
done
# Print the generated password
echo "Generated password: $password"
This script generates a random password based on user-defined criteria. It first defines character sets for lowercase letters, uppercase letters, numbers, and symbols. The user specifies the desired length of the password, which determines the number of characters the script will generate. Using a for loop, the script iterates through each position in the password length, randomly selecting characters from the concatenated character sets and appending them to the password string. Then it prints the generated password to the console for the user.
Here, a 10-digit password is generated automatically.
10. Image Converter
Image format conversion is a fundamental task in managing digital media. From JPEG to PNG, GIF to TIFF, the ability to seamlessly convert between formats ensures accessibility and usability across diverse platforms and devices. Execute the following script to convert all JPEG files in the current directory to PNG format concurrently:
#!/bin/bash
echo "Converting JPEG files to PNG concurrently:"
convert_image() {
echo "Converting: $1"
convert "$1" "${1%.jpg}.png"
}
for image in *.jpg; do
convert_image "$image" &
done
wait
echo "Conversion complete."
This Bash script concurrently converts JPEG files to PNG format. It begins by echoing a message indicating the conversion process has started. The convert_image
function is defined to convert each JPEG file to PNG using the ImageMagick package’s convert
command. Within a for loop, it iterates through all JPEG files in the current directory, invoking the convert_image
function for each file in the background using &
. The wait
command ensures all background processes are complete before echoing a message indicating that the format conversion is finished.
The script converts 2 images in JPEG format from the current directory to PNG format.
Note: If your system does not have the convert command, it’s likely that the command-line tool provided by the ImageMagick package, which includes the convert command, is not installed.Β Use your system’s package manager to install ImageMagick. Here is how you can do it in Ubuntu:
sudo apt install imagemagick
Practice Tasks on Bash βforβ Loop
If you aim to be better at using the βforβ loop in the Bash scripting, then you can try solving the following problems using the concept discussed in this article:
- Create a Bash script that renames all files in a directory with a specific extension (e.g., .txt) to include a timestamp using a for loop.
- Develop a Bash script that generates Pascal’s triangle, using the for loop.
- Develop a script that takes an array of strings as input and prints the elements in reverse order using a for loop.
- Write a Bash script that calculates the total size of all files in a directory and its subdirectories using a for loop.
- Create a script that periodically checks network connectivity by pinging remote servers. Log connection status and generate reports indicating downtime periods.
Conclusion
Mastering the for loop in Bash scripting opens doors to automating routine tasks effortlessly. Whether you are a Linux enthusiast or a scripting novice, I hope the examples presented in this article will sharpen your bash scripting skills.
People Also Ask
What is a loop in bash?
A loop in Bash is a programming construct used to execute a set of commands repeatedly based on certain conditions. It helps automate tasks by repeating actions without manual intervention. In Bash scripting, loops are essential for performing repetitive tasks efficiently. They enable the execution of commands or operations on multiple items or data sets, enhancing the efficiency of scripts and programs.
How to print a string list using bash for loop?
To print a list of strings using a Bash for loop, you can iterate through each string in the list and print it individually. First, define an array containing the strings you want to print using string_list=("string1" "string2" "string3" ... "stringN")
. Then, use a for loop to iterate through each element of the array using for item in "${string_list[@]}"
. Within the loop, access each element using array indexing and print it to the console with echo "$item"
.
How do I run a for loop in Linux?
To run a for loop in Linux, you can use the Bash shell scripting language. First, you need to define the structure of your loop, typically using the syntax: for variable in list; do command; done
. Here, for each iteration of the loop, the “variable” takes on the value of each item in the “list“, and the associated “command” is executed. This structure allows you to automate repetitive tasks efficiently in a Linux environment.
Can you nest for loops in Bash?
Yes, you can nest for loops in Bash to perform more complex iterations. The basic syntax for nesting for loops in Bash is as follows:
for outer_variable in outer_list; do
for inner_variable in inner_list; do
# Commands or actions to perform
done
done
In this structure, the outer loop iterates over the elements of the outer list, while the inner loop iterates over the elements of the inner list for each iteration of the outer loop. This allows for executing commands or actions for each combination of elements from both lists.
What is the structure of the for loop in Bash?
The structure of a for loop in Bash consists of defining a variable that iterates through a list of values. The basic syntax for a for loop in Bash is as follows:
for variable in list; do
# Commands to execute for each iteration
done
In this structure, the “variable” represents the variable that changes with each iteration, while the “list” is the list of values over which the variable iterates. Within the loop body, commands to execute for each value in the list can be added.
Related Articles
- How to Iterate Through List Using βforβ Loop in Bash
- How to Use Bash βforβ Loop with Variable [12 Examples]
- Bash Increment and Decrement Variable in βforβ Loop
- How to Use Bash Parallel βforβ Loop [7 Examples]
- How to Loop Through Array Using βforβ Loop in Bash
- How to Use Bash βforβ Loop with Range [5 Methods]
- How to Use Bash βforβ Loop with βseqβ Command [10 Examples]
- How to Use “for” Loop in Bash Files [9 Practical Examples]
- Usage of βforβ Loop in Bash Directory [5 Examples]
- How to Use βforβ Loop in One Line in Bash [7 Examples]
- How to Create Infinite Loop in Bash [7 Cases]
- How to Use Bash Continue with βforβ Loop [9 Examples]
<< Go Back to For Loop in Bash |Β Loops in Bash | Bash Scripting Tutorial