We use theifexpression tocheckthe pattern or command status and accordingly we can make certain decisions to execute scripts or commands.
The syntax of theifconditional is as follows:
if command
then
command
command
fi
From the preceding syntax, we can clearly understand the working of theifconditional construct. Initially,ifwill execute the command. If the result of command execution is true or 0, then all the commands that are enclosed betweenthenandfiwill be executed. If the status of command execution afterifis false or non-zero, then all the commands afterthenwill be ignored and the control of execution will directly go tofi.
Let’s learn another variation ofifconstructs.
Syntax:
if command
then
command
command
else
command
fi
In the preceding case, if the command afterifis successfully executed or the status variable?content is0, then all the commands afterthenwill be executed. If the result of the command is a failure or non-zero, then all the commands afterelsewill be executed.
For numeric or string expression evaluations usingif, the syntax is as follows:
if [ string/numeric expression ]
then
command
fi
Alternatively, use the following syntax:
if [[ string expression ]]
then
command
fi
Alternatively, use the following syntax:
if (( numeric expression ))
then
command
fi
A simple example of checking the status of the last command executed using the if construct is as follows:
#!/bin/bash
if [ $? -eq 0 ]
then
echo "Command was successful."
else
echo "Command was successful."
fi
Whenever we run any command, the exit status of the command will be stored in the ? variable. The preceding construct will be very useful in checking the status of the last command.
Numerical handling if constructs
Let’s learn aboutusingtheifconstruct for numerical decision-making.
We can use thetestcommand for finding which variable contains the smaller value:
$ X=10
$ y=20
$ (( x < y ))
$ echo $?
0
The result 0 shows that x is smaller than y.
In the shell script if_01.sh, we can use the test command along with the if construct for checking the equality of variables with numerical values as follows:
#!/bin/bash
a=100
if [ $a -eq 100 ]
then
echo "a is equal to $a"
else
echo "a is not equal"
fi
Let’s test the following program:
$ chmod +x if_01.sh
$ ./if_01.sh
The following will be the output after executing the preceding commands:
Output:a is equal to 100
Use the script if_02.sh to check which product is costly. The script is as follows:
#!/bin/bash
echo "Enter the cost of product a"
read a
echo "Enter the cost of product b"
read b
if [ $a -gt $b ]
then
echo " a is greater"
else
echo " b is greater"
fi
Let’s test the following program:
$ chmod +x if_02.sh
$ ./if_02.sh
The following will be the output after executing the preceding commands:
Output:Enter the cost of product a100
Enter the cost of product b150
b is greater
$
Using the exit command and the ? variable
If we need to terminate the shell script and come back to the command line, then we can use the exit command. The syntax is very simple:
exit 0
The given command will terminate the shell script and return to the command line. It will store the0value in the?status variable. We can use any value between0and255. Value0means success, and any other non-zero value means an error. We can use these values to indicate error information.
The script to check the value of a parameter that is passed along with the command (either less than0or greater than30) is as follows. This will save us from using the nestedifstatement:
#!/bin/bash
if (( $1 < 0 || $1 > 30 ))
then
echo "mdays is out of range"
exit 2
fi
The test command used in the preceding expression for OR can be written as follows:
[ $1 -lt 0 -o $1 -gt 30 ]
String handling with the if construct
Let’s learn aboutusingstring-related checking using theifexpression.
The following script,if_03.sh, will check the equality of two strings:
echo "Enter the first string to compare"
read name1
echo "Enter the Second string to compare"
read name2
if [ "$name1" == "$name2" ]
then
echo "First string is equal to Second string"
else
echo "Strings are not same"
fi
Let’s test the following program:
$ chmod +x if_03.sh
$ ./if_03.sh
The following will be the output after executing the preceding commands:
Output:$ ./ if_03.sh
Enter the first string to compare
LEVANA
Enter the Second string to compare
TECHNOLOGIES
Strings are not same
$ ./ if_03.sh
The following will be the output after executing the preceding commands:
Output:Enter the first string to compare
LEVANA
Enter the Second string to compare
LEVANA
First string is equal to Second string
$
We will write the script for performing various other string operations using a test. Let’s write the script if_04.sh to compare two strings for various attributes:
#!/bin/bash
str1="Ganesh"
str2="Naik"
if [ $str1 = $str2 ]
then
echo "Two Strings Are Equal"
fi
if [ $str1 != $str2 ]
then
echo "Two Strings are not equal"
fi
if [ $str1 ]
then
echo "String One Has Size Greater Than Zero"
fi
if [ $str2 ]
then
echo "String Two Has Size Greater Than Zero"
fi
Let’s test the following program:
$ chmod +x if_04.sh
$ ./if_04.sh
The following will be the output after executing the preceding commands:
Output:Two Strings are not equal
String One Has Size Greater Than Zero
String Two Has Size Greater Than Zero
If we want to verify whether the entered password is valid, then script if_05.sh will be as follows:
#!/bin/bash
stty -echo # password will not be printed on screen
read -p "Please enter a password :" password
if test "$password" == "Abrakadabra"
then
echo "Password is matching"
fi
stty echo
Let’s test the following program:
$ chmod +x if_05.sh
$ ./if_05.sh
The following will be the output after executing the preceding commands:
Output:$ ./if_05.sh
Please enter a password : levana
$ ./if_05.sh
Please enter a password : Abrakadabra
Password is matching
$
Checking for null values
Many a time we need to check the value of variable, such as whether it is null. The null value means zero value. If we want to create the string with the null value, then we should use double quotes ("") while declaring it:
if [ "$string" = "" ]
then
echo "The string is null"
fi
We can even use[ ! "$string" ]or[ -z "$string" ]for null checking of strings.
Let’s write the scriptif_08.sh, which will search for the entered person’s name and tell us whether the user is on the computer system:
#!/bin/bash
read -p "Enter a user name : " user_name
# try to locate username in in /etc/passwd
#
grep "^$user_name" /etc/passwd > /dev/null
status=$?
if test $status -eq 0
then
echo "User '$user_name' is found in /etc/passwd."
else
echo "User '$user_name' is not found in /etc/passwd."
fi
Let’s test the following program:
$ chmod +x if_08.sh
$ ./if_08.sh
The following will be the output after executing the preceding commands:
Output:Enter a user name : ganesh
User 'ganesh' is not found in /etc/passwd.
In the preceding script, we are searching for the username in the/etc/passwdfile. If a person’s name is not found in the/etc/passwdfile, then we can conclude that the username has not been created in the system.
Let’s write a script to check the disk space being used. The script will print a warning if 90 percent or more of the disk space is used on one of the mounted partitions.
The shell scriptif_09.shfor solving the disk filesystem usage warning will be as follows:
#!/bin/bash
df -h | grep /dev/sda1 | cut -c 35-36 > log.txt
read usage < log.txt
if [ $usage -gt 80 ]
then
echo "Warning - Disk file system has exceeded 80% !"
echo "Please move extra data to backup device."
else
echo "Good - You have enough disk space to continue working !"
fi
Let’s test the following program:
$ chmod +x if_09.sh
$ ./if_09.sh
If the preceding program does not work, due to some hardware differences, then make the following changes to the script:
- Check to see whether your partition for storage is
sda1,sda2, or any other by entering the$df -hcommand. - Check whether the
%disk utilization value is at character count35and36. If not, then make changes in the code accordingly.
Using the df command, we get the disk filesystem usage information. The grep command is filtering the hard disk partition, which contains our data. Then, we filter the disc % utilization number and store that value in the log.txt file. Using the read command, we read the % utilization and store it in the usage variable. Later on, using the if command, we check and warn the user if the % utilization is greater than 80
File handling with the if command
You have already learned about how tousethetestcommand for checking various file operations such as checking the file’s permissions and similar other attributes. A command’s task in any script is to check whether the file or folder is present or not. Then, accordingly, we need to proceed. We will see how to use theifcommand along with thetestcommand.
Use the simple scriptif_10.shto check whether the file exists or not in the current directory as follows:
#!/bin/bash
read filename
if test -e $filename
then
echo "file exists"
else
echo " file does not exist"
fi
Let’s test the program as follows:
$ chmod +x if_10.sh
$ ./if_10.sh
The following will be the output after executing the preceding commands:
Output:sample.txt
file does not exist
$ touch sample.txt
$ ./if_10.sh
sample.txt
file exists
First, we checked without the file. Then, we created a file with thetouchcommand. We can very easily check for the presence of the file.
Let’s learn how to use theifcommand to check various file attributes, such as whether it exists, whether it has file permissions to read, write, execute, and similar by writing scriptif_11.shas follows:
#!/bin/bash
echo "$1 is: "
if ! [ -e $1 ]
then
echo "..Do not exists"
exit
else
echo "file is present"
fi
if [ -x $1 ]
then
echo "..Executable"
fi
if [ -r $1 ]
then
echo "..Readable"
fi
if [ -w $1 ]
then
echo "..Writable"
fi
Let’s test the following program:
$ chmod +x if_11.sh
$ ./if_11.sh sample.txt
This should be the output:
Output:sample.txt is:"file is present"..Readable..Writable
The shell script if_12.sh for performing the file copy operation and then checking whether the copy operation was successful will be as follows:
#!/bin/bash
file1="File1"
file2="File2"
if cp $file1 $file2
then
echo "Copy Command Executed Successfully"
echo "Content of file named Fil1 copied in another file named File2"
else
echo "Some problem in command execution"
fi
Let’s test the program:
$ chmod +x if_12.sh
$ ./if_12.sh
The following will be the output after executing the preceding commands:
Output:$ touch File1
$ ./if_12.sh
Copy Command Executed Successfully
Content of file named Fil1 copied in another file named File2
Multiple test commands and if constructs
These type of constructs enable us to execute the second command depending on the success or failure of the first command:
command1 & command2
command1 || command2
Let’s write script if_13.sh. In this script, we will ask the user to input two numbers. Then, the if statement will evaluate two expressions. If both are true, then the command after then will be executed; otherwise, commands after else will be called:
#!/bin/bash
echo "Enter the first number"
read val_a
echo "Enter the Second number"
read val_b
if [ $val_a == 1 ] & [ $val_b == 10 ]
then
echo "testing is successful"
else
echo "testing is not successful"
fi
Let’s test the program:
$ chmod +x if_13.sh
$ ./if_13.sh
The following will be the output after executing the preceding commands:
Output:Enter the first number10
Enter the Second number20
testing is not successful
$ ./if_13.sh
Enter the first number1
Enter the Second number10
testing is successful
Sometimes, we may need to enter a command to check whether the file has the execute permission ? If it is executable, then the file should be executed. The script for such a requirement will be as follows:
test -e file & . file.
Let’s learn one more example of&and multiple expressions using thetestcommand. In the following script,if_14.sh, we will check whetherfile_oneis present, then we will printHelloand then immediately we will check whetherfile_twois present. Then we will printthereon the screen:
#!/bin/bash
touch file_one
touch file_two
if [ -f "file_one" ] & echo "Hello" & [ -f file_two ] & echo "there"
then
echo "in if"
else
echo "in else"
fiexit 0
Let’s test the program:
$ chmod +x if_14.sh
$ ./if_14.sh
The following will be the output after executing the preceding commands:
Output:Hellotherein if
The following script,if_15.sh, will check file permissions such as read, write, and execute in the sameifcommand using multiple&with thetestcommand:
#!/bin/bash
echo "Please enter file name for checking file permissions"
read file
if [[ -r $file & -w $file & -x $file ]]
then
echo "The file has read, write,and execute permission"
fi
Let’s test the program:
$ chmod +x if_15.sh
$ touch sample.txt
$ chmod +rwx sample.txt
$ ./if_15.sh sample.txt
The following will be the output after executing the preceding commands:
Output:The file has read, write, and execute permissions.
Till now, we have seen multiple expressions using the & logical operator. Now we will see one example with the OR (||) logical operator. In the following script, if_16.sh, we will check the existence of file_one and then we will print Hello on the screen. If the first expression of file checking fails, then the second expression of echo will be executed:
#!/bin/sh
if [ -f file_one ] || echo "Hello"
then
echo "In if"
else
echo "In else"
fi
Let’s test the program:
$ chmod +x if_16.sh
$ ./if_16.sh
The following will be the output after executing the preceding commands:
Output:helloIn if
$ touch file_one
$ ./if_16.sh
This is the output:
Output:In if
We checked in the preceding script whether file_one is absent or present.
The if/elif/else command
Sometimes, we need to make a decisiononmultiple situations or options, such as whether a city is the capital of a country, the state capital, a major city, or a small town. In such situations where, depending on various options, we need to execute different commands,if/elseorif/elif/elsedecision-making commands are useful.
Using theif/elif/elsecommands, we can have multiple decision-making processes. If theifcommand succeeds, the command afterthenwill be executed. If it fails, the command after theelifstatement will be tested. If that statement succeeds, then statements under theelifare executed. However, suppose none of theelifconditions are true, then statements after theelsecommand are executed. Here, theelseblock is executed by default. Thefistatement will close theif/elif/elsecommand.
The syntax of decision-making using theif elifconstruct is as follows:
If expression_1
then
Command
elif
expression_2
then
Command
elif
expression_3
then
Command
else
Command
fi
Let’s write script if_18.sh as follows. In this script, we are checking whether the directory with a given name exists or not. If this fails, then we are checking whether the file with the given name exists. Even if this fails, then we will inform the user that neither the file nor the directory exists with the given name:
#!/bin/bash
echo "Kindly enter name of directory : "
read file
if [[ -d $file ]]
then
echo "$file is a directory"
elif [[ -f $file ]]
then
echo "$file is a file."
else
echo "$file is neither a file nor a directory. "
fi
Let’s test the program:
$ chmod +x if_18.sh
$ ./if_18.sh
The following will be the output after executing the preceding commands:
Output:$ ./if_18.sh
Kindly enter name of directory :File1
File1 is a file.
$ mkdir dir1
$ ./if_18.sh
Kindly enter name of directory :dir1
dir1 is a directory
$ ./if_18.sh
Kindly enter name of directory :File007
File007 is neither a file nor a directory.
The null command
In many situations, we may need a command that does nothing and returns a success status such as 0. In such cases, we can use the null command. It is represented by a colon (:). For example, in the if loop, we do not want to add any command if it is successful, but we have certain commands to execute if it fails. In such situations, we can use the null command. This is illustrated in the following if_19.sh script. If we want to loop for ever, then the null command can be used in the for loop:
#!/bin/bash
city=London
if grep "$city" city_database_file >& /dev/null
then
:
else
echo "City is not found in city_database_file "
exit 1
fi
Let’s test the program:
$ chmod +x if_19.sh
$ ./if_19.sh
The following will be the output after executing the preceding commands
Output:City is not found in city_database_file
We can observe from the preceding script that the colon is a null command and it does nothing.
