0% found this document useful (0 votes)
28 views

Os Ass3

The document contains 14 programming assignments for shell scripts. The assignments cover topics like generating marksheets, finding the largest number, creating menus to run commands, listing files, checking file types, calculating factorials, finding HCF, making directories, counting file details, printing arrays, and building a basic calculator.

Uploaded by

Khushi sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Os Ass3

The document contains 14 programming assignments for shell scripts. The assignments cover topics like generating marksheets, finding the largest number, creating menus to run commands, listing files, checking file types, calculating factorials, finding HCF, making directories, counting file details, printing arrays, and building a basic calculator.

Uploaded by

Khushi sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

LAB ASSIGNMENT 3

PROGRAM 1:Write a shell script to generate marksheet of a student. Take 3 subjects, calculate
and display total marks, percentage and Class obtained by the student. Take marks from the user
terminal.
# Function to calculate total marks
calculate_total_marks() {
total=$((subject1 + subject2 + subject3))
echo $total
}

# Function to calculate percentage


calculate_percentage() {
percentage=$(echo "scale=2; ($1 / 300) * 100" | bc)
echo $percentage
}

# Function to determine class obtained


determine_class() {
if (( $(echo "$1 >= 80" | bc -l) )); then
echo "Distinction"
elif (( $(echo "$1 >= 60" | bc -l) )); then
echo "First Class"
elif (( $(echo "$1 >= 40" | bc -l) )); then
echo "Pass Class"
else
echo "Fail"
fi
}

# Taking input from the user


echo "Enter marks for Subject 1:"
read subject1
echo "Enter marks for Subject 2:"
read subject2
echo "Enter marks for Subject 3:"
read subject3

# Calculating total marks


total_marks=$(calculate_total_marks)

# Calculating percentage
percentage=$(calculate_percentage $total_marks)

# Determining class obtained


class_obtained=$(determine_class $percentage)

# Displaying marksheet
echo "-----------------------"
echo " MARKSHEET "
echo "-----------------------"
echo "Subject 1: $subject1"
echo "Subject 2: $subject2"
echo "Subject 3: $subject3"
echo "-----------------------"

Page no. 1
echo "Total Marks: $total_marks"
echo "Percentage: $percentage%"
echo "Class Obtained: $class_obtained"

PROGRAM 2: Write a shell script to find the largest among the 3 given numbers in UNIX / Linux.
Using looping statements.
# Function to find the largest number among three
find_largest() {
largest=$1
for num in "$@"; do
if [ $num -gt $largest ]; then
largest=$num
fi
done
echo $largest
}

# Taking input from the user


echo "Enter three numbers:"
read num1
read num2
read num3

# Finding the largest number


largest=$(find_largest $num1 $num2 $num3)

# Displaying the result


echo "The largest number among $num1, $num2, and $num3 is: $largest"

PROGRAM 3: Write a menu driven shell script which will print the following menu and execute
the given task.
a) Display calendar of current month
b) Display today’s date and time
c) Display usernames those are currently logged in the
system
d) Display your name at given x, y position
e) Display your terminal number
f) Exit
while true; do
# Displaying the menu
echo "MENU:"
echo "a) Display calendar of current month"
echo "b) Display today’s date and time"
echo "c) Display usernames those are currently logged in the system"

Page no. 2
echo "d) Display your name at given x, y position"
echo "e) Display your terminal number"
echo "f) Exit"
echo -n "Enter your choice: "
read choice

case $choice in
a)
# Display calendar of current month
cal
;;
b)
# Display today's date and time
date
;;
c)
# Display usernames currently logged in
who
;;
d)
# Display name at given x, y position
echo -n "Enter X position: "
read x
echo -n "Enter Y position: "
read y
tput cup $x $y
echo "Your Name"
;;
e)
# Display terminal number
tty
;;
f)
# Exit the program
echo "Exiting..."
exit 0
;;
*)
echo "Invalid option, please choose again."
;;
esac
done

Page no. 3
PROGRAM 4: Write a shell script that displays a list of all the files in the current directory.
# Displaying list of files in current directory
echo "List of files in the current directory:"
ls

PROGRAM 5: Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or a directory and reports accordingly. whenever the argument is
a file or directory.
# Function to check if argument is a file or directory and report accordingly
check_file_or_directory() {
if [ -e "$1" ]; then
if [ -f "$1" ]; then
echo "$1 is a file."
elif [ -d "$1" ]; then
echo "$1 is a directory."
else
echo "$1 is not a regular file or directory."
fi
else
echo "$1 does not exist."
fi
}

# Checking each argument


if [ $# -eq 0 ]; then
echo "No arguments provided."
else
for arg in "$@"; do
check_file_or_directory "$arg"
done
fi

PROGRAM 6: Write a shell script to find the factorial of given integer.


# Function to calculate factorial
factorial() {
if [ $1 -eq 0 ]; then
echo 1
else
local i=$1
local fact=1
while [ $i -gt 1 ]; do
fact=$((fact * i))
i=$((i - 1))
done
echo $fact
fi
}
# Taking input from the user
echo -n "Enter an integer: "
read num

# Checking if input is a positive integer


if [[ $num =~ ^[0-9]+$ ]]; then
result=$(factorial $num)

Page no. 4
echo "Factorial of $num is $result"
else
echo "Invalid input. Please enter a positive integer."
fi

PROGRAM 7: Write a Shell script to list all of the directory files in a directory
# Check if directory argument is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory="$1"
# Check if directory exists
if [ ! -d "$directory" ]; then
echo "Error: Directory '$directory' not found."
exit 1
fi

# List all files in the directory


echo "Files in directory '$directory':"
ls -l "$directory" | grep "^-" | awk '{print $9}'

PROGRAM 8: Write Shell Script to print multiplication table of a given number


# Function to print multiplication table
print_multiplication_table() {
num=$1
echo "Multiplication table of $num:"
for (( i=1; i<=10; i++ )); do
echo "$num x $i = $(($num * $i))"
done
}
# Taking input from the user
echo -n "Enter a number to print its multiplication table: "
read number

# Checking if input is a positive integer


if [[ $number =~ ^[0-9]+$ ]]; then
print_multiplication_table $number
else
echo "Invalid input. Please enter a positive integer."
fi

PROGRAM 9: Write Shell Script to calculate power of a number using while & for loop
# Function to calculate power of a number using while loop
calculate_power_while() {
base=$1

Page no. 5
exponent=$2
result=1
while [ $exponent -gt 0 ]; do
result=$((result * base))
exponent=$((exponent - 1))
done
echo $result
}

# Taking input from the user


echo -n "Enter base: "
read base
echo -n "Enter exponent: "
read exponent

# Calculating power using while loop


power=$(calculate_power_while $base $exponent)
echo "$base raised to the power of $exponent is: $power"

# Function to calculate power of a number using for loop


calculate_power_for() {
base=$1
exponent=$2
result=1
for ((i=1; i<=exponent; i++)); do
result=$((result * base))
done
echo $result
}

# Taking input from the user


echo -n "Enter base: "
read base
echo -n "Enter exponent: "
read exponent

# Calculating power using for loop


power=$(calculate_power_for $base $exponent)
echo "$base raised to the power of $exponent is: $power"

PROGRAM 10: Write Shell Script to find HCF of two numbers.


# Function to calculate HCF of two numbers
calculate_hcf() {
num1=$1
num2=$2

while [ $num2 -ne 0 ]; do


remainder=$((num1 % num2))
num1=$num2
num2=$remainder
done

echo "HCF of $1 and $2 is: $num1"


}

Page no. 6
# Taking input from the user
echo -n "Enter first number: "
read num1
echo -n "Enter second number: "
read num2

# Calculating HCF
calculate_hcf $num1 $num2

PROGRAM 11: Write Shell Script Make directory by checking existence.


# Function to make directory if it doesn't exist
make_directory() {
if [ ! -d "$1" ]; then
mkdir "$1"
echo "Directory '$1' created successfully."
else
echo "Directory '$1' already exists."
fi
}

# Taking input from the user


echo -n "Enter directory name: "
read directory_name

# Calling function to make directory


make_directory "$directory_name"

PROGRAM 12: Write Shell Script Counting characters, words & lines in the file.
# Function to count characters, words, and lines in a file
count_characters_words_lines() {
file="$1"

if [ ! -f "$file" ]; then
echo "Error: File '$file' not found."
exit 1
fi

characters=$(wc -m < "$file")


words=$(wc -w < "$file")
lines=$(wc -l < "$file")

echo "File: $file"


echo "Number of characters: $characters"
echo "Number of words: $words"
echo "Number of lines: $lines"
}

# Taking input from the user


echo -n "Enter file name: "
read filename

Page no. 7
# Calling function to count characters, words, and lines
count_characters_words_lines "$filename"

PROGRAM 13: Write Shell Script to print contents of an array.


# Define an array
my_array=("apple" "banana" "cherry" "date" "fig")

# Function to print contents of an array


print_array() {
echo "Contents of the array:"
for item in "${my_array[@]}"; do
echo "$item"
done
}

# Call the function to print the array


print_array

PROGRAM 14: Write Shell Script for simple calculator to perform addition subtraction
multiplication and division based on the symbol using case statements.
# Function to perform addition
addition() {
result=$(echo "$1 + $2" | bc)
echo "Result: $result"
}

# Function to perform subtraction


subtraction() {
result=$(echo "$1 - $2" | bc)
echo "Result: $result"
}

# Function to perform multiplication


multiplication() {
result=$(echo "$1 * $2" | bc)
echo "Result: $result"
}

# Function to perform division


division() {
if [ $2 -eq 0 ]; then
echo "Error: Division by zero is not allowed."
else
result=$(echo "scale=2; $1 / $2" | bc)
echo "Result: $result"
fi
}

Page no. 8
# Taking input from the user
echo "Enter the operation:"
read operation
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2

# Performing the operation based on the symbol


case $operation in
+)
addition $num1 $num2
;;
-)
subtraction $num1 $num2
;;
*)
echo "Invalid operation symbol. Please enter +, -, *, or /."
;;
esac

PROGRAM 15: Write Shell Script for Add array elements - Shell Script
# Define an array
my_array=(10 20 30 40 50)

# Function to add elements of the array


add_array_elements() {
sum=0
for item in "${my_array[@]}"; do
sum=$((sum + item))
done
echo "Sum of array elements: $sum"
}

# Call the function to add array elements


add_array_elements

PROGRAM 16: Write Shell Script reverse elements in array.


# Define an array
my_array=("apple" "banana" "cherry" "date" "fig")

# Function to reverse elements of the array


reverse_array_elements() {
reversed_array=()
for (( i=${#my_array[@]}-1; i>=0; i-- )); do
reversed_array+=("${my_array[$i]}")
done
echo "Reversed array:"
printf '%s\n' "${reversed_array[@]}"
}

Page no. 9
# Call the function to reverse array elements
reverse_array_elements

PROGRAM 17: Write shell script program to addition, subtraction, multiplication of two matrix.
# Function to transpose a matrix
transpose_matrix() {
local rows=$1
local cols=$2
local -n matrix=$3

local transposed=()
for ((j = 0; j < cols; j++)); do
for ((i = 0; i < rows; i++)); do
transposed[$((j * rows + i))]=${matrix[$i * $cols + $j]}
done
done

# Assigning transposed array back to the original array


for ((i = 0; i < rows; i++)); do
for ((j = 0; j < cols; j++)); do
matrix[$((i * cols + j))]=${transposed[$((j * rows + i))]}
done
done
}
# Function to add two matrices
add_matrices() {
local rows=$1
local cols=$2
local -n result=$3
local -n matrix1=$4
local -n matrix2=$5
for ((i = 0; i < rows; i++)); do
for ((j = 0; j < cols; j++)); do
result[$((i * cols + j))]=$((${matrix1[$((i * cols + j))]} + ${matrix2[$((i * cols + j))]}))
done
done
}
# Function to subtract two matrices
subtract_matrices() {
local rows=$1
local cols=$2
local -n result=$3
local -n matrix1=$4
local -n matrix2=$5

for ((i = 0; i < rows; i++)); do


for ((j = 0; j < cols; j++)); do
result[$((i * cols + j))]=$((${matrix1[$((i * cols + j))]} - ${matrix2[$((i * cols + j))]}))
done
done
}

# Function to multiply two matrices


multiply_matrices() {

Page no. 10
local rows1=$1
local cols1=$2
local cols2=$3
local -n result=$4
local -n matrix1=$5
local -n matrix2=$6
for ((i = 0; i < rows1; i++)); do
for ((j = 0; j < cols2; j++)); do
local sum=0
for ((k = 0; k < cols1; k++)); do
sum=$((sum + matrix1[$((i * cols1 + k))] * matrix2[$((k * cols2 + j))]))
done
result[$((i * cols2 + j))]=$sum
done
done
}

# Function to print a matrix


print_matrix() {
local rows=$1
local cols=$2
local -n matrix=$3

for ((i = 0; i < rows; i++)); do


for ((j = 0; j < cols; j++)); do
printf "%d " "${matrix[$((i * cols + j))]}"
done
echo
done
}
# Main script starts here
# Define matrix dimensions and elements
rows=3
cols=3
matrix1=(
123
456
789
)
matrix2=(
987
654
321
)

# Perform addition
add_result=()
add_matrices $rows $cols add_result matrix1 matrix2
echo "Addition of two matrices:"
print_matrix $rows $cols add_result
echo

# Perform subtraction
subtract_result=()
subtract_matrices $rows $cols subtract_result matrix1 matrix2
echo "Subtraction of two matrices:"
print_matrix $rows $cols subtract_result
echo

Page no. 11
# Perform multiplication
multiply_result=()
multiply_matrices $rows $cols $cols multiply_result matrix1 matrix2
echo "Multiplication of two matrices:"
print_matrix $rows $cols multiply_result

PROGRAM 18: Write Shell program to add two numbers using functions.
# Function to add two numbers
add_numbers() {
local result=$(( $1 + $2 ))
echo "The sum of $1 and $2 is: $result"
}

# Taking input from the user


echo -n "Enter first number: "
read num1
echo -n "Enter second number: "
read num2

# Calling the function to add two numbers


add_numbers $num1 $num2

PROGRAM 19: Write Shell Script to compare two strings in unix shell script.
# Taking input from the user
echo -n "Enter first string: "
read string1
echo -n "Enter second string: "
read string2

# Comparing the strings


if [ "$string1" == "$string2" ]; then
echo "The strings are equal."
else
echo "The strings are not equal."
fi

PROGRAM 20: Write a shell program to demonstrate Equal operator (=), Not Equal operator
(!=),Less than (\<),Greater than (\>) operation on two strings.
# Taking input from the user
echo -n "Enter first string: "
read string1
echo -n "Enter second string: "
read string2

Page no. 12
# Demonstrating comparison operators
echo "Comparison results:"
echo "-------------------"
echo "Equal operator (=):"
if [ "$string1" = "$string2" ]; then
echo "The strings are equal."
else
echo "The strings are not equal."
fi

echo "Not Equal operator (!=):"


if [ "$string1" != "$string2" ]; then
echo "The strings are not equal."
else
echo "The strings are equal."
fi

echo "Less than operator (<):"


if [ "$string1" \< "$string2" ]; then
echo "$string1 is less than $string2."
else
echo "$string1 is not less than $string2."
fi

echo "Greater than operator (>):"


if [ "$string1" \> "$string2" ]; then
echo "$string1 is greater than $string2."
else
echo "$string1 is not greater than $string2."
fi

PROGRAM 21: Write a Program for system calls of Unix operating systems (opendir, readdir,
closedir).
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main() {
DIR *directory;
struct dirent *entry;

// Open directory
directory = opendir(".");
if (directory == NULL) {
perror("Unable to open directory");
exit(EXIT_FAILURE);
}

// Read directory contents

Page no. 13
printf("Contents of the directory:\n");
while ((entry = readdir(directory)) != NULL) {
printf("%s\n", entry->d_name);
}

// Close directory
closedir(directory);

return 0;
}

PROGRAM 22: Write a Program for Process system calls of Unix operating systems (fork, getpid,
exit).
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
pid_t pid;

// Create a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
} else if (pid == 0) {
// Child process
printf("Child process:\n");
printf("PID: %d\n", getpid());
printf("Parent PID: %d\n", getppid());
// Child exits
exit(0);
} else {
// Parent process
printf("Parent process:\n");
printf("PID: %d\n", getpid());
printf("Child PID: %d\n", pid);
// Wait for child to finish
wait(NULL);
}
return 0;
}

Page no. 14
PROGRAM 23: Write the program to implement the system calls wait ( ) and exit ( ).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;

// Create a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
} else if (pid == 0) {
// Child process
printf("Child process is running...\n");
// Simulating some task in the child process
sleep(3);
printf("Child process is done.\n");
// Child exits
exit(42);
} else {
// Parent process
printf("Parent process is waiting for child...\n");
// Wait for child to finish and collect its exit status
wait(&status);
if (WIFEXITED(status)) {
printf("Child process exited with status: %d\n", WEXITSTATUS(status));
}
printf("Parent process is done.\n");
}
return 0;
}

PROGRAM 24: write a program to implement the system call execl ( ).


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
printf("Parent process executing...\n");

// Create a child process


pid_t pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(EXIT_FAILURE);

Page no. 15
} else if (pid == 0) {
// Child process
printf("Child process executing...\n");

// Replace the child process image with a new program


execl("/bin/ls", "ls", "-l", NULL);
// If execl() returns, it indicates failure
perror("execl() failed");
exit(EXIT_FAILURE);
} else {
// Parent process
printf("Parent process waiting for the child...\n");
wait(NULL);
printf("Parent process done.\n");
}

return 0;
}

PROGRAM 25: write a program to implement the system call execv ( ).


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
printf("Parent process executing...\n");

// Create a child process


pid_t pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process executing...\n");

// Define arguments for the new program


char *args[] = {"/bin/ls", "-l", NULL};

// Execute a new program using execv


if (execv("/bin/ls", args) == -1) {
perror("execv() failed");
exit(EXIT_FAILURE);
}
} else {
// Parent process
printf("Parent process waiting for the child...\n");
wait(NULL);
printf("Parent process done.\n");

Page no. 16
}

return 0;
}

PROGRAM 26: write a C program for I/O system calls.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define BUFFER_SIZE 4096

int main() {
int input_fd, output_fd; // File descriptors for input and output files
ssize_t bytes_read, bytes_written;
char buffer[BUFFER_SIZE];

// Open the input file


input_fd = open("input.txt", O_RDONLY);
if (input_fd == -1) {
perror("Failed to open input.txt");
exit(EXIT_FAILURE);
}

// Open or create the output file


output_fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (output_fd == -1) {
perror("Failed to open output.txt");
close(input_fd);
exit(EXIT_FAILURE);
}

// Read from the input file and write to the output file
while ((bytes_read = read(input_fd, buffer, BUFFER_SIZE)) > 0) {
bytes_written = write(output_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("Write error");
close(input_fd);
close(output_fd);
exit(EXIT_FAILURE);
}
}

if (bytes_read == -1) {
perror("Read error");
close(input_fd);
close(output_fd);

Page no. 17
exit(EXIT_FAILURE);
}

// Close the files


if (close(input_fd) == -1) {
perror("Failed to close input file");
exit(EXIT_FAILURE);
}
if (close(output_fd) == -1) {
perror("Failed to close output file");
exit(EXIT_FAILURE);
}

printf("File copied successfully.\n");

return 0;
}

Page no. 18

You might also like