Course Code: CAM23P Course Title: Shell Programming
Course Credits: 02 (0-0-2) Hours/Week: 04
Total Contact Hours: 60 Formative Assessment Marks: 10
Exam Marks: 40 Exam Duration: 03
Course Outcomes (COs):
On successful completion of this course, students will be able to:
1. Develop skill in shell scripting to perform simple operations and problems.
2. Perform file manipulation using shell scripts.
3. Understand and implement shell scripts for system information.
Laboratory Program List
Part A:
1. Write a shell script to swap 2 values.
2. Write a shell script to check if the given number is even or odd.
3. Write a shell script to find the largest of 3 numbers.
4. Write a shell script to perform arithmetic operations.
5. Write a shell script to find the sum of first 10 natural numbers.
6. Write a shell script to display multiplication table of a given number.
7. Write a shell script to find the length of a given string.
8. Write a shell script to find factorial of a given number.
9. Write a shell script which counts the numbers of lines and number of words present in a
given file.
10. Write a shell script to display the Fibonacci series upto N number.
Part B:
1. Shell script to search for particular element from an array of elements.
2. Shell script to calculate the TA, HRA and DA of an employee.
3. Shell script that displays a list of all files in the current directory to which the user has read write
and execute permissions.
4. Develop an interactive script that asks for a word and file name and then tells how many times
that word occurred in the file.
5. Shell script to extract a sub string from a given string.
6. Shell script to perform the following operations
a. Concatenate 2 strings
b. Rename a file
c. Delete a filed.
d. Copy the file
7. Shell script to display the
a)Version of the shell
b) The user information
c) Login date and time
d) List of processes running on the system
e) User home directory
8. C program to display PID of parent and PID of child process.
9. Shell script that takes two filename as arguments. It should check whether the contents of two
files are same or not, if they are same then second file should be deleted.
10. Assume a file with the given information
First Name Middle Name Age
-------------- ------------------ ------
Write a shell script to
a. Sort the first name in alphabetical order
b. Sort the age in terms of ascending order
c. Sort the age in terms of descending order
d. Sort the middle name in alphabetical order
Evaluation Scheme for Lab Examination [Marks: 40]
• Writing: One program from both Part A and Part B (15 Marks each) : 15 x 2 = 30
• Execution: Any one of the written Program: 05 Marks
• Viva: 05 Marks
Part A:
1. Write a shell script to swap 2 values.
echo "swapping using temprory variable"
echo "enter a "
read a
echo "enter b"
read b
c=$a
a=$b
b=$c
echo "afer swapping"
echo "$a"
echo "$b"
2. Write a shell script to check if the given number is even or odd.
read -p 'Enter a number :' num
if [ $(($num%2)) == 0 ]
then
echo The number is even
else
echo The number is odd
fi
3. Write a shell script to find the largest of 3 numbers.
echo "Enter Num1"
read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
then
echo $num1
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
then
echo $num2
else
echo $num3
fi
4. Write a shell script to perform arithmetic operations.
#!/bin/sh
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
5. Write a shell script to find the sum of first 10 natural numbers.
#!/bin/bash
sum=0
for ((i=1; i<=10; i++)); do
sum=$((sum + i))
done
echo "The sum of the first 10 natural numbers is: $sum"
6. Write a shell script to display multiplication table of a given number.
#!/bin/bash
# Prompt the user for a number
read -p "Enter a number: " num
# Validate if the input is a number
if ! [[ "$num" =~ ^[0-9]+$ ]]; then
echo "Invalid input. Please enter a positive integer."
exit 1
fi
# Display the multiplication table
echo "Multiplication Table for $num"
for i in {1..10}
do
echo "$num x $i = $((num * i))"
done
7. Write a shell script to find the length of a given string.
#!/bin/bash
# Prompt the user to enter a string
echo "Enter a string:"
read input_string
# Get the length of the string
string_length=${#input_string}
# Display the length
echo "The length of the string is: $string_length"
8. Write a shell script to find factorial of a given number.
#!/bin/bash
# Function to calculate factorial
factorial() {
num=$1
fact=1
for (( i=1; i<=num; i++ ))
do
fact=$((fact * i))
done
echo "Factorial of $num is $fact"
# Read input from the user
read -p "Enter a number: " number
# Check if input is a non-negative integer
if [[ $number =~ ^[0-9]+$ ]]; then
factorial $number
else
echo "Please enter a valid non-negative integer."
Fi
9. Write a shell script which counts the numbers of lines and number of words present in a
given file.
#!/bin/bash
# Check if a file is provided as an argument
if [ $# -ne 1 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
# Assign the provided file name to a variable
FILE=$1
# Check if the file exists
if [ ! -f "$FILE" ]; then
echo "Error: File '$FILE' not found!"
exit 1
fi
# Count the number of lines and words
LINE_COUNT=$(wc -l < "$FILE")
WORD_COUNT=$(wc -w < "$FILE")
# Display the results
echo "Number of lines in '$FILE': $LINE_COUNT"
echo "Number of words in '$FILE': $WORD_COUNT"
10. Write a shell script to display the Fibonacci series upto N number.
#!/bin/bash
# Function to generate Fibonacci series
fibonacci() {
num=$1
a=0
b=1
echo -n "$a $b "
for (( i=2; i<num; i++ ))
do
fib=$((a + b))
echo -n "$fib "
a=$b
b=$fib
done
echo ""
# Read input from user
echo -n "Enter the number of terms: "
read N
# Validate input
if ! [[ "$N" =~ ^[0-9]+$ ]] || [ "$N" -le 0 ]; then
echo "Please enter a valid positive integer."
exit 1
fi
# Call function
fibonacci $N
Part B:
1. Shell script to search for particular element from an array of elements.
#!/bin/bash
# Define an array
elements=("apple" "banana" "cherry" "date" "elderberry")
# Element to search for
read -p "Enter the element to search: " search_element
# Flag to check if element is found
found=0
# Loop through the array
for element in "${elements[@]}"; do
if [[ "$element" == "$search_element" ]]; then
found=1
break
fi
done
# Print result
if [[ $found -eq 1 ]]; then
echo "Element '$search_element' found in the array."
else
echo "Element '$search_element' not found in the array."
fi
2. Shell script to calculate the TA, HRA and DA of an employee.
#!/bin/bash
# Function to calculate allowances
calculate_allowances() {
local basic_salary=$1
# Define percentage values
ta_percentage=10 # TA is 10% of Basic Salary
hra_percentage=20 # HRA is 20% of Basic Salary
da_percentage=15 # DA is 15% of Basic Salary
# Calculate Allowances
ta=$(echo "scale=2; $basic_salary * $ta_percentage / 100" | bc)
hra=$(echo "scale=2; $basic_salary * $hra_percentage / 100" | bc)
da=$(echo "scale=2; $basic_salary * $da_percentage / 100" | bc)
# Print the results
echo "-----------------------------"
echo "Basic Salary: ₹$basic_salary"
echo "Travel Allowance (TA): ₹$ta"
echo "House Rent Allowance (HRA): ₹$hra"
echo "Dearness Allowance (DA): ₹$da"
echo "-----------------------------"
# Read Basic Salary from user
read -p "Enter Basic Salary: " basic_salary
# Validate if input is a number
if ! [[ "$basic_salary" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
echo "Invalid input! Please enter a valid number."
exit 1
fi
# Call function to calculate allowances
calculate_allowances "$basic_salary"
Example Run:
$ ./salary_calc.sh Enter Basic Salary: 50000
-----------------------------
Basic Salary: ₹50000
Travel Allowance (TA): ₹5000.00
House Rent Allowance (HRA): ₹10000.00
Dearness Allowance (DA): ₹7500.00
-----------------------------
3. Shell script that displays a list of all files in the current directory to which the user has read write
and execute permissions.
#!/bin/bash
echo "Files with read, write, and execute permissions for the user:"
for file in *; do
if [ -f "$file" ] && [ -r "$file" ] && [ -w "$file" ] && [ -x "$file" ]; then
echo "$file"
fi
done
How to Use:
1. Save the script as list_rw_files.sh.
2. Give it execute permission:
chmod +x list_rw_files.sh
3. Run the script:
./list_rw_files.sh
4. Develop an interactive script that asks for a word and file name and then tells how many times
that word occurred in the file.
def count_word_occurrences(file_name, word):
try:
with open(file_name, 'r', encoding='utf-8') as file:
content = file.read()
word_count = content.lower().split().count(word.lower())
print(f"The word '{word}' occurred {word_count} times in the file '{file_name}'.")
except FileNotFoundError:
print("Error: File not found. Please enter a valid file name.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
file_name = input("Enter the file name: ")
word = input("Enter the word to count: ")
count_word_occurrences(file_name, word)
This script will prompt the user for a file name and a word, then count and display how many times
that word appears in the file. Let me know if you need any modifications!
4. Shell script to extract a sub string from a given string.
Using cut (if the substring is based on position)
#!/bin/bash
str="Hello, World!"
sub_str=$(echo "$str" | cut -c8-12) # Extract characters from position 8 to 12
echo "Substring: $sub_str"
Output:
World
Using awk (if you need flexibility with delimiters)
#!/bin/bash
str="Hello,World,Shell,Script"
sub_str=$(echo "$str" | awk -F',' '{print $2}') # Extract second field
echo "Substring: $sub_str"
Output:
World
Using sed (if extracting using regex)
#!/bin/bash
str="Hello, World!"
sub_str=$(echo "$str" | sed -E 's/Hello, (.*)!/\1/')
echo "Substring: $sub_str"
Output:
World
6. Shell script to perform the following operations
a. Concatenate 2 strings
b. Rename a file
c. Delete a filed.
d. Copy the file
#!/bin/bash
# a. Concatenate 2 strings
echo "Enter first string:"
read str1
echo "Enter second string:"
read str2
concatenated="$str1$str2"
echo "Concatenated string: $concatenated"
# b. Rename a file
echo "Enter the file to rename:"
read old_filename
echo "Enter the new name for the file:"
read new_filename
mv "$old_filename" "$new_filename"
echo "File renamed to $new_filename"
# c. Delete a file
echo "Enter the file to delete:"
read file_to_delete
rm "$file_to_delete"
echo "File $file_to_delete deleted."
# d. Copy a file
echo "Enter the file to copy:"
read file_to_copy
echo "Enter the destination filename:"
read destination_file
cp "$file_to_copy" "$destination_file"
echo "File copied to $destination_file"
7. Shell script to display the
a)Version of the shell
b) The user information
c) Login date and time
d) List of processes running on the system
e) User home directory
#!/bin/bash
echo "============================="
echo " System Information Script"
echo "============================="
# a) Version of the shell
echo "Shell Version: $BASH_VERSION"
# b) User information
echo "User Information: $(whoami)"
# c) Login date and time
echo "Login Date and Time: $(who -u | awk '{print $1, $3, $4}')"
# d) List of processes running on the system
echo "Running Processes:"
ps -e --format "pid,cmd"
# e) User home directory
echo "User Home Directory: $HOME"
echo "============================="
echo " Script Execution Completed"
echo "============================="
How to Run:
1. Save the script as sysinfo.sh.
2. Give execution permission:
chmod +x sysinfo.sh
3. Run the script:
./sysinfo.sh
8. C program to display PID of parent and PID of child process.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid; // Declare a variable to store process ID
pid = fork(); // Create child process
if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
else if (pid == 0) {
// This block executes in the child process
printf("Child Process: PID = %d, Parent PID = %d\n", getpid(), getppid());
else {
// This block executes in the parent process
printf("Parent Process: PID = %d, Child PID = %d\n", getpid(), pid);
return 0;
Sample Output:
Parent Process: PID = 1234, Child PID = 1235
Child Process: PID = 1235, Parent PID = 1234
9. Shell script that takes two filename as arguments. It should check whether the contents of two
files are same or not, if they are same then second file should be deleted.
#!/bin/bash
# Check if two arguments are provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <file1> <file2>"
exit 1
fi
file1=$1
file2=$2
# Check if both files exist
if [ ! -f "$file1" ]; then
echo "Error: File '$file1' does not exist."
exit 1
fi
if [ ! -f "$file2" ]; then
echo "Error: File '$file2' does not exist."
exit 1
fi
# Compare the contents of the two files
if cmp -s "$file1" "$file2"; then
echo "Files are the same. Deleting '$file2'."
rm "$file2"
else
echo "Files are different. No deletion performed."
Fi
You can run the script like this:
./script.sh file1.txt file2.txt
10. Assume a file with the given information
First Name Middle Name Age
-------------- ------------------ ------
Write a shell script to
a. Sort the first name in alphabetical order
b. Sort the age in terms of ascending order
c. Sort the age in terms of descending order
d. Sort the middle name in alphabetical order
data.txt
FirstName MiddleName Age
--------------------- ------
Alice Marie 30
Bob John 25
Charlie Ann 35
David Lee 28
Eve Rose 22
sort_script.sh
#!/bin/bash
# Define the input file
INPUT_FILE="data.txt"
# Sort by First Name (Alphabetically)
echo "Sorting by First Name (Alphabetically):"
sort -k1,1 $INPUT_FILE
echo -e "\nSorting by Age (Ascending Order):"
sort -k3,3n $INPUT_FILE
echo -e "\nSorting by Age (Descending Order):"
sort -k3,3nr $INPUT_FILE
echo -e "\nSorting by Middle Name (Alphabetically):"
sort -k2,2 $INPUT_FILE
Execution:
1. Save this script as sort_script.sh.
2. Ensure data.txt is in the same directory.
3. Give execution permission:
chmod +x sort_script.sh
4. Run the script:
./sort_script.sh