Unit – 4 Shell Scripting and Statements
Shell Definition:
In shell programming, a shell is a command-line interpreter that provides
a user interface for interacting with the operating system. It allows users
to execute commands, run scripts, and manage system processes. The
shell interprets the commands entered by the user and communicates with
the operating system kernel to execute them.
Popular shell types include Bash (Bourne Again Shell), Zsh (Z Shell),
and Csh (C Shell) etc.
set, unset and echo,Read command with shell variables:
1. read
The read command is used to take input from the user or a file. It reads a
line of text from standard input (keyboard or a file) and assigns it to a
variable.
Syntax:
read variable_name
Example:
read name echo "Hello, $name"
2. echo
The echo command is used to print text or variable values to the screen
(standard output). It's commonly used to display messages or the results
of commands.
Syntax:
echo [options] [string]
Example:
echo "Hello, World!"
1
Unit – 4 Shell Scripting and Statements
3. set
The set command is used to configure or display shell options and
environment variables. It can be used to enable or disable specific shell
features.
Syntax
set [options]
Example
set -x # Enables debugging mode, showing each command before
executing
4. unset
The unset command is used to remove a shell variable or function,
effectively "deleting" it from the environment.
Syntax
unset variable_name
Example:
unset myvar
Positional Parameters in shell programming:
Positional Parameters in shell programming are variables that store
command-line arguments passed to a shell script or function. These
parameters are automatically assigned to specific variables, allowing you
to access the arguments within your script. They are referenced using
numbers and special symbols.
2
Unit – 4 Shell Scripting and Statements
Shell Script for Positional Parameters:
Program:
# Display the name of the script
echo "Script Name: $0"
# Display the first three positional parameters
echo "First parameter: $1"
echo "Second parameter: $2"
echo "Third parameter: $3"
# Display the total number of arguments passed to the script
echo "Number of arguments: $#"
# Display all arguments passed to the script
echo "All arguments: $@"
Output:
Script Name: ./main.sh
First parameter: Hello
Second parameter: World
Third parameter: 123
Number of arguments: 3
All arguments: Hello World 123
3
Unit – 4 Shell Scripting and Statements
Logical Operators:
Conditional statements such as if, while, or test commands. They help in
controlling the flow of the script based on multiple conditions.
AND Operator (&&)
The AND operator is used to execute a command or statement only if the
previous command succeeds (i.e., returns an exit status of 0). If all
conditions or commands return true (i.e., exit status 0), the combined
condition is true.
Syntax:
command1 && command2
Example:
[ $a -lt 10 ] && [ $b -gt 5 ]
OR Operator (||)
The OR operator is used to execute a command if the previous command
fails (i.e., returns a non-zero exit status). If at least one condition is true,
the combined condition is true.
Syntax:
command1 || command2
Example:
[ $a -gt 10 ] || [ $b -lt 5 ]
NOT Operator (!)
The NOT operator (!) in shell programming is used to invert the result of
a command or condition.
Syntax:
! Condition
4
Unit – 4 Shell Scripting and Statements
Decision Statements:
Types of Decision Statements in Shell PRogramming:
1. if Statements
2. if...else Statement
3. if...elif...else Statement
4. case Statments
In shell programming, decision statements allow you to control the flow
of a script by executing different commands based on conditions. The
most common decision statements include if, else, elif, case, and test.
Below is a breakdown of these decision statements:
1. if Statement
The if statement is used to test conditions and execute commands based
on the result. It is one of the most fundamental decision-making
structures.
Syntax:
if [ condition ]
# Commands to execute if condition is true
fi
2. if...else Statement
The if...else statement allows for two alternative paths: one if the
condition is true, and another if the condition is false.
5
Unit – 4 Shell Scripting and Statements
Syntax:
if [ condition ]
then
# Commands to execute if condition is true
else
# Commands to execute if condition is false
fi
3. if...elif...else Statement
The if...elif...else statement allows for multiple conditions to be checked
in sequence, each with its own commands to execute if true.
Syntax:
if [ condition1 ]
then
# Commands if condition1 is true
elif [ condition2 ]
then
# Commands if condition2 is true
else
# Commands if all conditions are false
fi
4. case Statement
6
Unit – 4 Shell Scripting and Statements
The case statement is used when you need to match a variable or
expression against multiple patterns. It works similarly to switch
statements in other programming languages.
Syntax:
case $variable in
pattern1)
# Commands for pattern1
;;
pattern2)
# Commands for pattern2
;;
*)
# Default case (if no patterns match)
;;
esac
5. test Command
The test command evaluates conditions and is often used in conjunction
with if statements. In Bash, square brackets [] are a shorthand for test.
Syntax:
test condition
# or
[ condition ]
7
Unit – 4 Shell Scripting and Statements
Arithmetic in Shell script
Arithmetic operations in shell scripting allow you to perform
mathematical calculations within your scripts.
1. Using expr Command
The expr command evaluates expressions and performs arithmetic
operations.
Syntax:
expr operand1 operator operand2
2. Using bc Command
For more complex arithmetic (especially with floating-point numbers),
you can use the bc command (Basic Calculator).
Syntax:
echo "expression" | bc
8
Unit – 4 Shell Scripting and Statements
Here are some examples of numeric comparisons:
-lt : less than.
-gt : greater than.
-le : less than or equal to.
-ge : greater than or equal to.
-eq : equal to.
-ne : not equal to.
Examples:
9
Unit – 4 Shell Scripting and Statements
Shell Scripts:
1. Write a shell script to scans the name of the command and
executes it.
Program :-
echo "enter command name"
read cmd
$cmd
Output :-
enter command name
cal
February 2016
Su Mo Tu We Th Fr Sa
123456
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
2. Write a shell script Which works like calculator and performs
below operations such as
Addition ,Subtract ,Division ,Multiplication
Program :- using if..elif statement
echo " Enter one no."
read n1
echo "Enter second no."
read n2
echo "1.Addition"
echo "2.Subtraction"
echo "3.Multiplication"
echo "4.Division"
echo "Enter your choice"
read ch
if [ $ch = "1" ]
then
sum=`expr $n1 + $n2`
echo "Sum ="$sum
10
Unit – 4 Shell Scripting and Statements
elif [ $ch = "2" ]
then
sub=`expr $n1 - $n2`
echo "Sub = "$sub
elif [ $ch = "3" ]
then
mul=`expr $n1 \* $n2`
echo "Mul = "$mul
elif [ $ch = "4" ]
then
div=`expr $n1 / $n2`
echo "Div = "$div
fi
Output :-
Enter one no.
32
Enter second no.
12
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice
2
Sub = 20
3. Write a shell script to find the largest among the 3 given numbers.
Program :-
echo "Enter first number: "
read a
echo "Enter second number: "
read b
echo "Enter third number: "
read c
if [ $a -ge $b ]&&[ $a -ge $c ]
then
echo "$a is largest integer"
11
Unit – 4 Shell Scripting and Statements
elif [ $b -ge $a ]&&[ $b -ge $c ]
then
echo "$b is largest integer"
elif [ $c -ge $a ]&&[ $c -ge $b ]
then
echo "$c is largest integer"
fi
Output :-
Enter first number:
22
Enter second number:
33
Enter third number:
42
44 is largest integer
4. Write a shell script which displays a list of all files in the current
directory to which you have read, write and execute permissions
Program :-
for File in *
do
#Checks if the file is readable (-r), writable (-w), and executable (-x). The
-a option is used to combine these conditions.
if [ -r $File -a -w $File -a -x $File ]
then
echo $File
fi
done
Output :-
Desktop
Documents
Downloads
lab
Music
12
Unit – 4 Shell Scripting and Statements
5. Write a Shell Script to Check if a Number is Positive, Negative, or
Zero.
Program:
#!/bin/bash
echo -n "Enter a number: "
read num
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
6. Write a shell script to check if a number entered by the user is
even or odd.
Program:
#!/bin/bash
echo -n "Enter a number: "
read num
if [ $((num % 2)) -eq 0 ]; then
echo "The number is even."
else
echo "The number is odd."
fi
7. Write a shell script to check whether a directory exists, and if not,
create it.
Program:
#!/bin/bash
13
Unit – 4 Shell Scripting and Statements
echo -n "Enter the directory name: "
read dirname
if [ -d "$dirname" ]; then
echo "Directory '$dirname' already exists."
else
mkdir "$dirname"
echo "Directory '$dirname' created."
fi
8. Write a shell script that deletes all the files in the current
directory which are 0 bytes in length.
Program :-
clear
find . -name "*" -size -1k –delete
echo “files deleted”
Output :-
files deleted
9. Write a shell script presents a simple menu to the user with five
options using case Statements:
Display current date and time
List files in the current directory
Show the current user
Display disk usage
Exit
Hint :
· date: Displays the current date and time.
· ls: Lists files in the current directory.
· whoami: Shows the current user’s username.
· df -h: Displays disk usage in a human-readable format.
Program:
#!/bin/bash
14
Unit – 4 Shell Scripting and Statements
# Display menu options
echo "Choose an option:"
echo "1. Display current date and time"
echo "2. List files in the current directory"
echo "3. Show the current user"
echo "4. Display disk usage"
echo "5. Exit"
echo -n "Enter your choice (1-5): "
# Read user input
read choice
# Case statement to handle user input
case $choice in
1)
echo "Current date and time: $(date)"
;;
2)
echo "Files in the current directory:"
ls
;;
3)
echo "Current user: $(whoami)"
;;
4)
echo "Disk usage:"
df -h
;;
5)
echo "Exiting..."
exit 0
;;
*)
echo "Invalid choice. Please select a number between 1 and 5."
;;
esac
15
Unit – 4 Shell Scripting and Statements
For Practice:
10. Write a Shell Script to make following file and directory
management operations menu based: (Using Case Statement)
Display Current Directory
List Directory
Make Directory
Copy a File
Rename a File
Delete a File
Edit a File
11. Write a Shell Script which reads a text file and output the
following:
Count of character, words and line
File in Reverse
Frequency of PArticular word in the file.
Lower case letter in place of upper case letter
12. Write a Shell Script to Check if a User is Logged In.
13. Environmental variable
14. Test (with position parameters)
15. Set (with position parameters)
16. Unset (with position parameters)
17. Shift (with position parameters)
18. Write a shell script to demonstrate read & echo statement using
Variable.
16