This is Part II of The Shell script for Beginners. If you have not read Part -I read It and then come back, as this blog is the continuation of Part-I.
Conditional logic
Conditional logic is a fundamental concept in programming that allows you to make decisions based on certain conditions. It's a powerful tool that enables you to write scripts that can adapt to changing conditions and make decisions based on the results of tests or evaluations. In this article, we'll be exploring conditional logic in shell scripts and how you can use it to write scripts that are more dynamic and flexible.
In shell scripts, conditional logic is implemented using control structures, such as if
statements. An if
statement allows you to execute a block of code only if a certain condition is met. Here's a simple example of an if
statement in a shell script:
#!/bin/bash
a=10
b=20
if [ $a -gt $b ]; then
echo "$a is greater than $b"
else
echo "$a is not greater than $b"
fi
In this example, the if
statement tests whether $a
is greater than $b
using the -gt
operator. If the test is true, the script will output "$a is greater than $b"
. If the test is false, the script will output "$a is not greater than $b"
.
Conditional logic in shell scripts can also be used to test multiple conditions using the elif
(else if) statement. An elif
statement allows you to specify additional tests that will be performed if the first if
test fails. Here's an example of an if
-elif
statement in a shell script:
#!/bin/bash
a=10
b=20
if [ $a -gt $b ]; then
echo "$a is greater than $b"
elif [ $a -eq $b ]; then
echo "$a is equal to $b"
else
echo "$a is less than $b"
fi
In this example, if the first if
test fails, the script will perform a second test to see if $a
is equal to $b
using the -eq
operator. If the second test is true, the script will output "$a is equal to $b"
. If both tests are false, the script will output "$a is less than $b"
.
Another control structure that can be used for conditional logic in shell scripts is the case
statement. A case
statement allows you to perform multiple tests on a single value, similar to a switch statement in other programming languages. Here's an example of a case
statement in a shell script:
#!/bin/bash
fruit="apple"
case $fruit in
"apple")
echo "The fruit is an apple.";;
"banana")
echo "The fruit is a banana.";;
"cherry")
echo "The fruit is a cherry.";;
*)
echo "The fruit is something else.";;
esac
In this example, the case
statement tests the value of the variable $fruit
against a series of patterns. If a pattern matches the value, the corresponding block of code will be executed. If no patterns match, the *
case will be executed, which acts as a catch-all. In this example, the script will output "The fruit is an apple."
.
Conditional operators
Conditional operators are used to test conditions in shell scripts and return a boolean value (true
or false
) based on the result of the test. Here is a table of common conditional operators in shell scripting:
Operator | Description | Example | Result |
-eq | Equal to | [ $a -eq $b ] | True if $a is equal to $b , otherwise false. |
-ne | Not equal to | [ $a -ne $b ] | True if $a is not equal to $b , otherwise false. |
-gt | Greater than | [ $a -gt $b ] | True if $a is greater than $b , otherwise false. |
-ge | Greater than or equal to | [ $a -ge $b ] | True if $a is greater than or equal to $b , otherwise false. |
-lt | Less than | [ $a -lt $b ] | True if $a is less than $b , otherwise false. |
-le | Less than or equal to | [ $a -le $b ] | True if $a is less than or equal to $b , otherwise false. |
\= | Equal to (string comparison) | [ $a = $b ] | True if $a is equal to $b , otherwise false. |
!= | Not equal to (string comparison) | [ $a != $b ] | True if $a is not equal to $b , otherwise false. |
Here's an example of how you can use conditional operators in a shell script:
#!/bin/bash
a=10
b=20
if [ $a -gt $b ]; then
echo "$a is greater than $b"
else
echo "$a is not greater than $b"
fi
In this example, the script uses the -gt
operator to test whether $a
is greater than $b
. If the test is true, the script outputs "$a is greater than $b"
. If the test is false, the script outputs "$a is not greater than $b"
.
It's important to note that when using conditional operators in shell scripts, you need to enclose the test expression in square brackets ([ ]
). This is because the square brackets are used to invoke the test
command, which performs the actual test.
In addition to the numeric and string comparison operators, there are also conditional operators specifically for testing files and directories. These operators are useful when writing scripts that manipulate files and directories and need to check certain conditions before proceeding with the script. Here's a table of common conditional operators for files and directories:
Operator | Description | Example | Result |
-e | File exists | [ -e /path/to/file ] | True if the file exists, otherwise false. |
-d | Directory exists | [ -d /path/to/directory ] | True if the directory exists, otherwise false. |
-f | File is a regular file (not a directory) | [ -f /path/to/file ] | True if the file is a regular file, otherwise false. |
-L | File is a symbolic link | [ -L /path/to/file ] | True if the file is a symbolic link, otherwise false. |
-r | File is readable | [ -r /path/to/file ] | True if the file is readable, otherwise false. |
-w | File is writable | [ -w /path/to/file ] | True if the file is writable, otherwise false. |
-x | File is executable | [ -x /path/to/file ] | True if the file is executable, otherwise false. |
Here's an example of how you can use conditional operators to test files and directories in a shell script:
#!/bin/bash
file_path=/path/to/file
if [ -e $file_path ]; then
if [ -f $file_path ]; then
echo "$file_path is a regular file"
elif [ -d $file_path ]; then
echo "$file_path is a directory"
else
echo "$file_path is not a regular file or a directory"
fi
else
echo "$file_path does not exist"
fi
In this example, the script first checks if the file at $file_path
exists using the -e
operator. If the file exists, the script then checks if it's a regular file using the -f
operator. If it's a regular file, the script outputs "$file_path is a regular file"
. If it's not a regular file, the script checks if it's a directory using the -d
operator. If it's a directory, the script outputs "$file_path is a directory"
. If it's neither a regular file nor a directory, the script outputs "$file_path is not a regular file or a directory"
. If the file does not exist, the script outputs "$file_path does not exist"
.
By using these conditional operators for files and directories, you can write scripts that are more robust and capable of handling different types of files and directories, making it easier to automate tasks and respond to changing conditions in your file system.
Loops
Loops are a fundamental construct in shell scripting that allow you to repeat a set of commands multiple times. There are two main types of loops in shell scripting: for
loops and while
loops.
For Loops
A for
loop allows you to repeat a set of commands for a fixed number of times or for each item in a list. The general syntax for a for
loop is:
for VARIABLE in LIST; do
commands
done
Where VARIABLE
is a variable that will take on the values in LIST
, and commands
are the commands that you want to repeat. The do
keyword signals the start of the commands to be executed, and the done
keyword signals the end of the loop.
Here's an example of a for
loop that prints the numbers from 1 to 10:
#!/bin/bash
for i in {1..10}; do
echo $i
done
This script uses the {1..10}
syntax to generate a list of numbers from 1 to 10. The for
loop then iterates over this list, and for each iteration, the value of $i
is set to the current number in the list. The echo
command then outputs the value of $i
.
You can also use a for
loop to iterate over the items in an array or a list of files in a directory. Here's an example of a for
loop that prints the items in an array:
#!/bin/bash
colors=("red" "green" "blue")
for color in "${colors[@]}"; do
echo $color
done
In this example, the for
loop iterates over the items in the colors
array, and for each iteration, the value of $color
is set to the current item in the array. The echo
command then outputs the value of $color
.
While Loops
A while
loop allows you to repeat a set of commands while a certain condition is true. The general syntax for a while
loop is:
while CONDITION; do
commands
done
Where CONDITION
is a command that returns either true or false, and commands
are the commands that you want to repeat. The do
keyword signals the start of the commands to be executed, and the done
keyword signals the end of the loop.
Here's an example of a while
loop that prints the numbers from 1 to 10:
#!/bin/bash
i=1
while [ $i -le 10 ]; do
echo $i
i=$((i + 1))
done
In this example, the while
loop continues to execute the echo
command and increment the value of $i
as long as $i
is less than or equal to 10. The [ $i -le 10 ]
syntax is used to test the condition, and it returns true as long as $i
is less than or equal to 10.
By using for
loops and while
loops, you can write scripts that repeat a set of commands multiple times, making it easier to automate tasks and process large amounts of data.
Conclusion
In conclusion, we have covered several key concepts in shell scripting including variables, input, arithmetic operations, conditional logic, and loops. Understanding and using these concepts can greatly enhance your ability to write effective shell scripts for automating various tasks.
We learned about variables, which are used to store and manipulate data in your script, and how to take input from the user using the read
command. Arithmetic operations are used for performing mathematical calculations in shell scripts, and conditional logic allows you to make decisions based on specific conditions.
Finally, we discussed the two main types of loops in shell scripting: for
and while
. These loops allow you to repeat a set of commands multiple times and are essential for processing large amounts of data or automating complex tasks.
By mastering these concepts, you will have a solid foundation for writing effective and efficient shell scripts. Whether you are a beginner or an experienced shell scripter, taking the time to understand and practice these concepts can greatly enhance your ability to write useful scripts for automating various tasks.