Conditional Statements and Loop in Bash Scripting for BCA | MCA | BSC-IT
Mastering conditional statements and loops in Bash scripting is essential for students pursuing BCA, MCA, or BSc-IT. These fundamental concepts enable you to create powerful and efficient scripts that can automate tasks, manage system operations, and process data effectively. In this guide, we will explore the basics of conditional statements and loops in Bash scripting, providing you with the knowledge and skills needed to tackle complex problems and enhance your programming capabilities. Whether you are a beginner or looking to strengthen your scripting proficiency, this comprehensive overview will serve as a valuable resource in your academic and professional journey.
Conditional Statements and Loops in Bash Scripting |
Conditional Statements in Bash Scripting
Conditional statements in Bash are used to make decisions in your scripts. They allow you to execute certain pieces of code only if specific conditions are met. One of the most common conditional statements are
- If-Else Statement
- Case Statements
If-Else Statements
Conditional statements allow you to make decisions in your scripts based on
certain conditions. The most common conditional statement in Bash is the
if-else
statement. It works by checking if a condition is true
and then performing an action based on whether it is true or false.
Basic Syntax
The basic syntax of a if-else
statement in Bash is as follows:
if [ condition ]; then
# Code to execute if the condition is true
else
# Code to execute if the condition is false
fi
if [ condition ]
: Checks if the condition is true.-
then
: If the condition is true, execute the code after this keyword. -
else
: If the condition is false, execute the code after this keyword. fi
: Ends theif-else
statement.
Example:
Let's say we want to check if a number is greater than 10. If it is, we print "The number is greater than 10". Otherwise, we print "The number is not greater than 10".
#!/bin/bash
read -p "Enter a number: " number
if [ $number -gt 10 ]; then
echo "The number is greater than 10"
else
echo "The number is not greater than 10"
fi
-
read -p "Enter a number: " number
: Prompts the user to enter a number. -
[ $number -gt 10 ]
: Checks if the number is greater than 10. -gt
: Stands for "greater than".
Using elif
Sometimes, you might need to check multiple conditions. This is where
elif
(short for "else if") comes in handy. The
elif
statement allows you to check another condition if the
previous if
condition was false.
Basic Syntax:
if [ condition1 ]; then
# Code to execute if condition1 is true
elif [ condition2 ]; then
# Code to execute if condition2 is true
else
# Code to execute if none of the conditions are true
fi
-
elif [ condition2 ]
: Checks the second condition if the first condition is false.
Example:
#!/bin/bash
read -p "Enter a number: " number
if [ $number -gt 10 ]; then
echo "The number is greater than 10"
elif [ $number -eq 10 ]; then
echo "The number is equal to 10"
else
echo "The number is less than 10"
fi
Let's extend our previous example to check if the number is greater than 10, equal to 10, or less than 10.
[ $number -eq 10 ]
: Checks if the number is equal to 10.-eq
: Stands for "equal to".
In this script:
- If the number is greater than 10, it prints "The number is greater than 10".
- If the number is equal to 10, it prints "The number is equal to 10".
- If neither condition is true, it prints "The number is less than 10".
Case Statements in Bash Scripting: Syntax and Examples
What is a Case Statement?
A case statement in Bash is like a switch statement in other programming
languages. It allows you to execute different blocks of code based on the
value of a variable or an expression. It's a way to simplify complex
if-else
statements.
Syntax of a Case Statement
Here's the basic syntax of a case statement in Bash:
case variable in
pattern1)
# code to execute if variable matches pattern1
;;
pattern2)
# code to execute if variable matches pattern2
;;
*)
# code to execute if variable doesn't match any pattern
;;
esac
-
case variable in
- This starts the case statement and checks the value of thevariable.
-
pattern1)
- This checks if the variable matchespattern1
. -
;;
- This marks the end of the code block forpattern1
. -
*)
- This is a default case that runs if none of the patterns match. -
esac
- This ends the case statement (it's "case" spelled backward).
Example: Simple Menu
Let's look at a simple example. Suppose you want to create a menu script that performs different actions based on user input.
#!/bin/bash
echo "Choose an option:"
echo "1) Display date and time"
echo "2) List files in current directory"
echo "3) Show current directory"
echo "4) Exit"
read -p "Enter your choice [1-4]: " choice
case $choice in
1)
echo "The current date and time is: $(date)"
;;
2)
echo "Files in current directory are: "
ls
;;
3)
echo "You are in directory: $(pwd)"
;;
4)
echo "Exiting the script. Goodbye!"
exit 0
;;
*)
echo "Invalid choice, please enter a number between 1 and 4."
;;
esac
Breakdown of the Example:
- Prompt the User: The script displays a menu with four options.
-
Read User Input: The
read
command takes the user's choice and stores it in the variablechoice
. - Case Statement:
-
case $choice in
- This checks the value ofchoice
. -
1)
- Ifchoice
is1
, it displays the current date and time using thedate
command. -
2)
- Ifchoice
is2
, it lists the files in the current directory using thels
command. -
3)
- Ifchoice
is3
, it shows the current directory using thepwd
command. -
4)
- Ifchoice
is4
, it exits the script with a goodbye message. -
*)
- Ifchoice
is anything other than1
,2
,3
, or4
, it displays an error message.
Practical Tips:
-
Patterns Can Be More Complex: Patterns can include
wildcards (
*
,?
) to match more complex conditions. -
Multiple Patterns: You can have multiple patterns leading
to the same code block by separating them with
|
(e.g.,pattern1|pattern2)
).
Example: Matching File Extensions
Here's another example that prints a message based on the file extension:
#!/bin/bash
read -p "Enter a filename: " filename
case $filename in
*.jpg|*.jpeg)
echo "This is a JPEG image file."
;;
*.png)
echo "This is a PNG image file."
;;
*.txt)
echo "This is a text file."
;;
*)
echo "File type is unknown."
;;
esac
Breakdown of the Example:
- Prompt the User: Asks the user to enter a filename.
-
Case Statement:
-
case $filename in
- Checks the value offilename
. -
*.jpg|*.jpeg)
- If the filename ends with.jpg
or.jpeg
, it prints a message saying it's a JPEG image file. -
*.png)
- If the filename ends with.png
, it prints a message saying it's a PNG image file. -
*.txt)
- If the filename ends with.txt
, it prints a message saying it's a text file. -
*)
- If the filename doesn't match any of the patterns, it prints a message saying the file type is unknown.
-
Loop in Bash Scripting
Loops are a fundamental part of Bash scripting, allowing you to execute a set
of commands repeatedly. There are three main types of loops in Bash:
for
loops, while
loops, and
until
loops. Let's break them down with simple examples.
1. For Loops
What They Do: For loops are used to iterate over a list of items or a range of numbers, executing commands for each item or number.
Basic Syntax:
for item in list
do
commands
done
Example:
#!/bin/bash
# A simple for loop to print numbers from 1 to 5
for number in 1 2 3 4 5
do
echo "Number: $number"
done
Iterating Over a Range:
#!/bin/bash
# A for loop to print numbers from 1 to 5 using a range
for number in {1..5}
do
echo "Number: $number"
done
2. While Loops
What They Do: While loops execute a set of commands as long as a given condition is true.
Basic Syntax:
while condition
do
commands
done
Example:
#!/bin/bash
# A while loop to print numbers from 1 to 5
number=1
while [ $number -le 5 ]
do
echo "Number: $number"
number=$((number + 1))
done
3. Until Loops
What They Do: Until loops are similar to while loops, but they execute the commands as long as the given condition is false.
Basic Syntax:
until condition
do
commands
done
Example:
#!/bin/bash
# An until loop to print numbers from 1 to 5
number=1
until [ $number -gt 5 ]
do
echo "Number: $number"
number=$((number + 1))
done
Detailed Explanation of Loop with Simple Examples
1. For Loops: Iterating Over Lists and Ranges
Lists:
- Imagine you have a list of fruits and you want to print each fruit's name.
Example:
#!/bin/bash
# A for loop to print names of fruits
for fruit in apple banana cherry
do
echo "Fruit: $fruit"
done
Explanation: This loop goes through each item in the list (apple, banana, cherry) and prints it.
Ranges:
- Suppose you want to print numbers from 1 to 5.
Example:
#!/bin/bash
# A for loop to print numbers from 1 to 5 using a range
for number in {1..5}
do
echo "Number: $number"
done
Explanation: This loop is used {1..5}
to create a
range of numbers from 1 to 5 and prints each number.
2. While Loops: Basic Syntax and Examples
Counting Up:
- You want to print numbers from 1 to 5 using a while loop.
Example:
#!/bin/bash
# A while loop to print numbers from 1 to 5
number=1
while [ $number -le 5 ]
do
echo "Number: $number"
number=$((number + 1))
done
Explanation: The loop runs as long as the condition
[ $number -le 5 ]
is true. It starts with number 1 and adds 1
each time until it reaches 5.
Counting Down:
- You want to print numbers from 5 to 1 using a while loop.
Example:
#!/bin/bash
# A while loop to print numbers from 5 to 1
number=5
while [ $number -ge 1 ]
do
echo "Number: $number"
number=$((number - 1))
done
Explanation: The loop runs as long as the condition
[ $number -ge 1 ]
is true. It starts with number 5 and subtracts
1 each time until it reaches 1.
3. Until Loops: Syntax and Use Cases
Basic Example:
#!/bin/bash
# An until loop to print numbers from 1 to 5
number=1
until [ $number -gt 5 ]
do
echo "Number: $number"
number=$((number + 1))
done
- You want to print numbers from 1 to 5 using an until loop.
Example:
Explanation: The loop runs until the condition
[ $number -gt 5 ]
becomes true. It starts with the number 1 and adds
1 each time until the number is greater than 5.
Practical Use Case:
- Suppose you want to keep prompting a user for a correct password until they get it right.
Example:
#!/bin/bash
# An until loop to prompt for a correct password
correct_password="secret"
input_password=""
until [ "$input_password" == "$correct_password" ]
do
read -p "Enter the password: " input_password
done
echo "Correct password entered!"
Explanation: The loop continues to prompt the user for a password until the entered password matches the correct one.
Summary
- For Loops: Best for iterating over a list of items or a range of numbers.
- While Loops: Best for running commands as long as a condition is true.
- Until Loops: Best for running commands until a condition becomes true.