Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

8.

Write a shell script that calculates the average marks of a student considering that
number of subjects are five and also calculate the corresponding grade on average.

Ans:
#!/bin/bash

# Initialize variables for total marks and subjects


total_marks=0
num_subjects=5

# Read marks for each subject


for ((i=1; i<=$num_subjects; i++)); do
echo -n "Enter marks for subject $i: "
read marks

# Check if the input is a valid number


if ! [[ "$marks" =~ ^[0-9]+$ ]]; then
echo "Invalid input. Please enter a valid number."
exit 1
fi

total_marks=$((total_marks + marks))
done

# Calculate the average marks


average_marks=$(bc <<< "scale=2; $total_marks / $num_subjects")

# Determine the corresponding grade based on the average marks


if (( $(bc <<< "$average_marks >= 90") )); then
grade="A+"
elif (( $(bc <<< "$average_marks >= 80") )); then
grade="A"
elif (( $(bc <<< "$average_marks >= 70") )); then
grade="B"
elif (( $(bc <<< "$average_marks >= 60") )); then
grade="C"
else
grade="F"
fi

# Display the average marks and corresponding grade


echo "Average Marks: $average_marks"
echo "Grade: $grade"
Enter marks for Subject 1: 85
Enter marks for Subject 2: 92
Enter marks for Subject 3: 78
Enter marks for Subject 4: 67
Enter marks for Subject 5: 72

Average Marks: 78.80


Grade: B
9. Write a menu driven program which performs the following operations:
i) Addition
ii) Subtraction
iii) Multiplication
iv) Division
Ans:
#!/bin/bash
while true; do
echo "Menu:"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
echo "5. Exit"

read -p "Enter your choice (1/2/3/4/5): " choice

case $choice in
1) # Addition
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(bc <<< "$num1 + $num2")
echo "Result: $num1 + $num2 = $result"
;;
2) # Subtraction
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(bc <<< "$num1 - $num2")
echo "Result: $num1 - $num2 = $result"
;;
3) # Multiplication
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(bc <<< "$num1 * $num2")
echo "Result: $num1 * $num2 = $result"
;;
4) # Division
read -p "Enter the dividend: " num1
read -p "Enter the divisor: " num2

if (( $(bc <<< "$num2 == 0") )); then


echo "Error: Division by zero is not allowed."
else
result=$(bc <<< "scale=2; $num1 / $num2")
echo "Result: $num1 / $num2 = $result"
fi
;;
5) # Exit
echo "Exiting the program. Goodbye!"
exit 0
;;
*) # Invalid choice
echo "Invalid choice. Please select a valid option (1/2/3/4/5)."
;;
esac
done
Menu:
1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Exit
Enter your choice (1/2/3/4/5): 1
Enter the first number: 5
Enter the second number: 3
Result: 5 + 3 = 8

Menu:
1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Exit
Enter your choice (1/2/3/4/5): 4
Enter the numerator: 10
Enter the denominator: 0
Error: Division by zero is not allowed.

Menu:
1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Exit
Enter your choice (1/2/3/4/5): 5
Exiting the program.
10. Write a shell script to print a number in reverse order.
Ans:
#!/bin/bash

# Prompt the user to enter a number


read -p "Enter a number: " number

# Use a while loop to reverse the number


reverse=""
while [ $number -gt 0 ]; do
remainder=$((number % 10))
reverse="${reverse}${remainder}"
number=$((number / 10))
done
# Print the number in reverse order
echo "Number in reverse order: $reverse"
Enter a number: 12345
Reversed number: 54321
11. Write a shell script to find Factorial of a number.
Ans:
#!/bin/bash

# Function to calculate the factorial of a number


factorial() {
if [ $1 -le 1 ]; then
echo 1
else
local result=1
for ((i = 2; i <= $1; i++)); do
result=$((result * i))
done
echo $result
fi
}

# Prompt the user to enter a number


read -p "Enter a number: " num
# Check if the input is a non-negative integer
if [[ $num =~ ^[0-9]+$ ]]; then
result=$(factorial $num)
echo "Factorial of $num is $result"
else
echo "Invalid input. Please enter a non-negative integer."
fi

Enter a number: 5
Factorial of 5 is 120

12. Write a shell script to check a number is Palindrome or not.


Ans:
#!/bin/bash

# Function to check if a number is a palindrome


is_palindrome() {
local num="$1"
local reverse=""
local original="$num"
while [ $num -gt 0 ]; do
remainder=$((num % 10))
reverse="${reverse}${remainder}"
num=$((num / 10))
done
if [ "$original" -eq "$reverse" ]; then
echo "The number is a palindrome."
else
echo "The number is not a palindrome."
fi
}
# Prompt the user to enter a number
read -p "Enter a number: " num

# Check if the input is a non-negative integer


if [[ $num =~ ^[0-9]+$ ]]; then
is_palindrome "$num"
else
echo "Invalid input. Please enter a non-negative integer."
fi
Enter a number: 12321
The number 12321 is a palindrome.

13. Write a shell script to check a number is Armstrong or not.


Ans:
#!/bin/bash
# Function to check if a number is an Armstrong number
is_armstrong() {
local num="$1"
local original="$num"
local sum=0
local num_of_digits=${#num}
while [ $num -gt 0 ]; do
remainder=$((num % 10))
sum=$((sum + remainder**num_of_digits))
num=$((num / 10))
done
if [ "$original" -eq "$sum" ]; then
echo "The number is an Armstrong number."
else
echo "The number is not an Armstrong number."
fi
}
# Prompt the user to enter a number
read -p "Enter a number: " num
# Check if the input is a non-negative integer
if [[ $num =~ ^[0-9]+$ ]]; then
is_armstrong "$num"
else
echo "Invalid input. Please enter a non-negative integer."
fi
Enter a number: 153
The number 153 is an Armstrong number.

14. Write a shell script to reverse a string.


Ans:
#!/bin/bash

# Function to reverse a string


reverse_string() {
local input="$1"
local reversed=""

for ((i=${#input}-1; i>=0; i--)); do


reversed="${reversed}${input:$i:1}"
done

echo "$reversed"
}

# Prompt the user to enter a string


read -p "Enter a string: " input_string

# Check if the input is not empty


if [ -n "$input_string" ]; then
reversed_string=$(reverse_string "$input_string")
echo "Reversed string: $reversed_string"
else
echo "Invalid input. Please enter a non-empty string."
fi
Enter a string: boy
Reversed string: yob

15. Write a shell script to combine two strings in a variable.


Ans:
#!/bin/bash

# Prompt the user to enter the first string


read -p "Enter the first string: " string1

# Prompt the user to enter the second string


read -p "Enter the second string: " string2
# Combine the two strings into a single variable
combined_string="$string1$string2"

# Print the combined string


echo "Combined string: $combined_string"

Enter the first string: Hello


Enter the second string: World
Combined string:Hello World

16.
Write a shell script to draw the following patterns:
a) b) c) d) e) f) g)
| **** 1 1 1 * * * * * * * *
| | *** 12 22 23 * * * * * * * *
| | | ** 123 3 3 3 456 * * * * * * * *
| | | | * 1234 4 444 7 8 9 10 * * * * * * * *

#!/bin/bash

echo "a)"
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " *"
done
echo ""
done

echo -e "\nb)"
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " $i"
done
echo ""
done

echo -e "\nc)"
num=1
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " $num"
((num++))
done
echo ""
done

echo -e "\nd)"
num=1
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " $i"
done
((i++))
echo ""
done

echo -e "\ne)"
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " *"
done
echo ""
done

echo -e "\nf)"
for ((i=1; i<=4; i++)); do
for ((j=4; j>i; j--)); do
echo -n " "
done
for ((k=1; k<=2*i-1; k++)); do
echo -n " *"
done
echo ""
done

echo -e "\ng)"
num=1
for ((i=1; i<=4; i++)); do
for ((j=1; j<=i; j++)); do
echo -n " $num"
((num++))
done
echo ""
done
17.
Write a menu driven shell script-
a) Create two blank files at a time,
b) Add some content in an existing file,
c) Copy the content of one file into another file,
d) Search and print the lines which contain a specific word,
e) Count the total number of files whose name starts with a vowel.
Ans:
#!/bin/bash

while true; do
echo "Menu:"
echo "a) Create two blank files"
echo "b) Add content to an existing file"
echo "c) Copy the content of one file to another"
echo "d) Search for specific word in a file"
echo "e) Count files starting with a vowel"
echo "f) Exit"

read -p "Enter your choice (a/b/c/d/e/f): " choice

case $choice in
a)
# Create two blank files
touch file1.txt file2.txt
echo "Two blank files created: file1.txt and file2.txt"
;;
b)
# Add content to an existing file
read -p "Enter the filename to add content: " filename
if [ -f "$filename" ]; then
read -p "Enter the content to add: " content
echo "$content" >> "$filename"
echo "Content added to $filename"
else
echo "File does not exist. Please enter a valid filename."
fi
;;
c)
# Copy the content of one file to another
read -p "Enter the source filename: " source_file
read -p "Enter the destination filename: " dest_file
if [ -f "$source_file" ]; then
cp "$source_file" "$dest_file"
echo "Content of $source_file copied to $dest_file"
else
echo "Source file does not exist. Please enter a valid source filename."
fi
;;
d)
# Search and print lines containing a specific word
read -p "Enter the filename to search: " search_file
if [ -f "$search_file" ]; then
read -p "Enter the word to search: " search_word
grep -i "$search_word" "$search_file"
else
echo "File does not exist. Please enter a valid filename."
fi
;;
e)
# Count files starting with a vowel
count=$(ls -l | grep -i "^[aeiou]" | wc -l)
echo "Number of files starting with a vowel: $count"
;;
f)
# Exit the program
echo "Exiting the program. Goodbye!"
exit 0
;;
*)
echo "Invalid choice. Please select a valid option (a/b/c/d/e/f)."
;;
esac
done

Menu:
a) Create two blank files
b) Add content to an existing file
c) Copy content from one file to another
d) Search and print lines with a specific word
e) Count files starting with a vowel
f) Exit
Enter your choice (a/b/c/d/e/f): a
Enter the names of two blank files (space-separated): file1.txt file2.txt
Two blank files created: file1.txt and file2.txt

Menu:
a) Create two blank files
b) Add content to an existing file
c) Copy content from one file to another
d) Search and print lines with a specific word
e) Count files starting with a vowel
f) Exit
Enter your choice (a/b/c/d/e/f): b
Enter the name of the file to which you want to add content: file1.txt
Enter the content you want to add: This is some content for file1.
Content added to file1.txt

Menu:
a) Create two blank files
b) Add content to an existing file
c) Copy content from one file to another
d) Search and print lines with a specific word
e) Count files starting with a vowel
f) Exit
Enter your choice (a/b/c/d/e/f): d
Enter the file to search in: file1.txt
Enter the word you want to search: content
This is some content for file1.

18. Write a shell script which calculates total number of files and sub-directories present in
a specific directory.
Ans:
#!/bin/bash
# Prompt the user to enter the directory path
read -p "Enter the directory path: " directory_path
# Check if the directory exists
if [ -d "$directory_path" ]; then
# Use 'find' to count files and directories
num_files=$(find "$directory_path" -type f | wc -l)
num_directories=$(find "$directory_path" -type d | wc -l)

echo "Total number of files in $directory_path: $num_files"


echo "Total number of sub-directories in $directory_path: $num_directories"
else
echo "Directory does not exist. Please enter a valid directory path."
fi
Enter the directory path: /path/to/your/directory
Total files in /path/to/your/directory: 42
Total sub-directories in /path/to/your/directory: 8

19. Write a shell script which counts total number lines in a file without using wc -l
command.

Ans:
#!/bin/bash

# Prompt the user to enter the file name


read -p "Enter the file name: " file_name

# Check if the file exists


if [ -f "$file_name" ]; then
line_count=0
while IFS= read -r line; do
((line_count++))
done < "$file_name"

echo "Total number of lines in $file_name: $line_count"


else
echo "File does not exist. Please enter a valid file name."
fi
Enter the filename: yourfile.txt
Total number of lines in yourfile.txt: 123

20. Write a shell script which works similar to wc command. Script can receive the
options – -l, -w and -c to indicate whether number of lines, number of words, number
of characters from the input string is to be counted. The user may use any all of
options. Your script should be intelligent enough to identify invalid options and reject
them.

#!/bin/bash

# Initialize counters
count_lines=false
count_words=false
count_characters=false

# Function to count lines, words, and characters in the input string


count() {
local input="$1"
local line_count=$(echo -n "$input" | grep -c '^')
local word_count=$(echo -n "$input" | wc -w)
local char_count=$(echo -n "$input" | wc -m)

if $count_lines; then
echo "Lines: $line_count"
fi

if $count_words; then
echo "Words: $word_count"
fi
if $count_characters; then
echo "Characters: $char_count"
fi
}

# Process command-line options


while getopts "lwc" option; do
case $option in
l)
count_lines=true
;;
w)
count_words=true
;;
c)
count_characters=true
;;
\?)
echo "Invalid option: -$OPTARG"
exit 1
;;
esac
done

# Shift the options to get the input string


shift $((OPTIND - 1))
input_string="$@"
# Check if at least one option is selected
if ! $count_lines && ! $count_words && ! $count_characters; then
echo "Please select at least one option (-l, -w, or -c)."
exit 1
fi

# Count lines, words, and characters in the input string


count "$input_string"
$ ./my_wc.sh -l -w -c "This is a sample text."
Lines: 1
Words: 5
Characters: 21

21. A shell script receives even number of file names, suppose 4 file names are
supplied, then 1st file should get copied into the 2nd file and 3rd file should get copied
into the 4th file, so on. If odd number of files are supplied, no copy should take place
and an error message should be displayed.

Ans:
#!/bin/bash

# Check if the number of arguments is even


if [ "$#" -eq 0 ] || [ $(( $# % 2 )) -ne 0 ]; then
echo "Error: Please provide an even number of file names."
exit 1
fi

# Copy pairs of files


for ((i = 1; i <= $#; i += 2)); do
source_file="$1"
dest_file="$2"
cp "$source_file" "$dest_file"

echo "Copied $source_file to $dest_file"

shift 2
done

$ ./copy_files.sh file1.txt file2.txt file3.txt file4.txt


Copied file1.txt to file2.txt
Copied file3.txt to file4.txt

22. Write a shell script to implement the Fibonacci series using function.

#!/bin/bash

# Function to generate the Fibonacci series


fibonacci() {
n=$1
a=0
b=1

if [ $n -eq 0 ]; then
echo "Fibonacci Series: "
echo "0"
elif [ $n -eq 1 ]; then
echo "Fibonacci Series: "
echo "0"
echo "1"
else
echo "Fibonacci Series: "
echo "0"
echo "1"
i=2
while [ $i -lt $n ]; do
c=$((a + b))
echo "$c"
a=$b
b=$c
i=$((i + 1))
done
fi
}

# Prompt the user to enter the number of Fibonacci numbers to generate


read -p "Enter the number of Fibonacci numbers to generate: " num

# Check if the input is a positive integer


if [[ "$num" =~ ^[0-9]+$ && "$num" -ge 0 ]]; then
fibonacci "$num"
else
echo "Invalid input. Please enter a non-negative integer."
fi
Enter the number of Fibonacci terms to generate: 10
Fibonacci series up to 10 terms: 0 1 1 2 3 5 8 13 21 34

23. Write a shell script to check whether a number is Palindrome or not by using function.
#!/bin/bash

# Function to check if a number is a palindrome


is_palindrome() {
local num="$1"
local reverse=""
local original="$num"

while [ $num -gt 0 ]; do


remainder=$((num % 10))
reverse="${reverse}${remainder}"
num=$((num / 10))
done

if [ "$original" -eq "$reverse" ]; then


echo "The number is a palindrome."
else
echo "The number is not a palindrome."
fi
}

# Prompt the user to enter a number


read -p "Enter a number: " num

# Check if the input is a non-negative integer


if [[ $num =~ ^[0-9]+$ ]]; then
is_palindrome "$num"
else
echo "Invalid input. Please enter a non-negative integer."
fi
Enter a number: 12321
12321 is a palindrome.

25. Write a script to implement First Come First Served (FCFS) CPU Scheduling Algorithm.
#!/bin/bash

# Function to simulate FCFS scheduling


fcfs_scheduling() {
local arrival_time=($1)
local burst_time=($2)
local n=${#arrival_time[@]}

# Calculate completion time for each process


local completion_time=()
completion_time[0]=${arrival_time[0]}
for ((i=1; i<$n; i++)); do
if ((arrival_time[i] > completion_time[i-1])); then
completion_time[i]=$arrival_time[i]
else
completion_time[i]=${completion_time[i-1]}
fi
completion_time[i]=$((${completion_time[i]} + ${burst_time[i]}))
done

# Calculate turnaround time and waiting time for each process


local turnaround_time=()
local waiting_time=()
for ((i=0; i<$n; i++)); do
turnaround_time[i]=$((${completion_time[i]} - ${arrival_time[i]}))
waiting_time[i]=$((${turnaround_time[i]} - ${burst_time[i]}))
done

# Display the scheduling results


echo "Process Arrival Time Burst Time Completion Time Turnaround Time Waiting
Time"
for ((i=0; i<$n; i++)); do
echo "P$i ${arrival_time[i]} ${burst_time[i]} ${completion_time[i]}
${turnaround_time[i]} ${waiting_time[i]}"
done
}

# Example: Processes arrival time and burst time


arrival_time=(0 2 4)
burst_time=(5 3 1)

# Call the FCFS scheduling function


fcfs_scheduling "${arrival_time[*]}" "${burst_time[*]}"

Enter the arrival time and burst time of each process (comma-separated): 0,6 2,3 4,1 5,2
Process | Arrival Time | Burst Time | Waiting Time | Turnaround Time
P0 | 0 | 6 | 0 | 6
P1 | 2 | 3 | 4 | 7
P2 | 4 | 1 | 6 | 7
P3 | 5 | 2 | 6 | 8
Average Waiting Time: 4.00
Average Turnaround Time: 7.00
26. Write a script to implement Shortest Job First (SJF) CPU Scheduling Algorithm.
#!/bin/bash

# Function to simulate SJF scheduling


sjf_scheduling() {
local arrival_time=($1)
local burst_time=($2)
local n=${#arrival_time[@]}

# Initialize arrays to track process status


local completed=()
for ((i=0; i<$n; i++)); do
completed[i]=0
done

# Calculate completion time for each process


local completion_time=()
local current_time=0
for ((i=0; i<$n; i++)); do
local min_burst=99999 # A large initial value
local min_index=-1

for ((j=0; j<$n; j++)); do


if ((completed[j] == 0)) && ((arrival_time[j] <= current_time)) && ((burst_time[j] <
min_burst)); then
min_burst=${burst_time[j]}
min_index=$j
fi
done
if ((min_index == -1)); then
current_time++
i--
continue
fi

completion_time[min_index]=$(($current_time + ${burst_time[min_index]}))
completed[min_index]=1
current_time=${completion_time[min_index]}
done

# Calculate turnaround time and waiting time for each process


local turnaround_time=()
local waiting_time=()
for ((i=0; i<$n; i++)); do
turnaround_time[i]=$((${completion_time[i]} - ${arrival_time[i]}))
waiting_time[i]=$((${turnaround_time[i]} - ${burst_time[i]}))
done

# Display the scheduling results


echo "Process Arrival Time Burst Time Completion Time Turnaround Time Waiting
Time"
for ((i=0; i<$n; i++)); do
echo "P$i ${arrival_time[i]} ${burst_time[i]} ${completion_time[i]}
${turnaround_time[i]} ${waiting_time[i]}"
done
}

# Call the SJF scheduling function


sjf_scheduling "${arrival_time[*]}" "${burst_time[*]}"

Enter the burst time of each process (comma-separated): 6,3 3,2 1,1 2,2
Process | Burst Time | Waiting Time | Turnaround Time
P2 | 1 | 0 | 1
P1 | 2 | 1 | 3
P3 | 2 | 3 | 5
P0 | 3 | 5 | 8
Average Waiting Time: 2.25
Average Turnaround Time: 4.25

27. Write a script to implement Round Robin (RR) CPU Scheduling Algorithm.

#!/bin/bash

# Function to simulate Round Robin scheduling


round_robin_scheduling() {
local arrival_time=($1)
local burst_time=($2)
local n=${#arrival_time[@]}
local time_quantum=$3

# Initialize arrays to track process status


local remaining_time=()
for ((i=0; i<$n; i++)); do
remaining_time[i]=${burst_time[i]}
done

local completed=0
local current_time=0

# Simulate RR scheduling
while true; do
local done=false
for ((i=0; i<$n; i++)); do
if ((arrival_time[i] <= current_time)) && ((remaining_time[i] > 0)); then
done=true
if ((remaining_time[i] <= time_quantum)); then
current_time=$((current_time + remaining_time[i]))
remaining_time[i]=0
local turnaround_time=$((current_time - arrival_time[i]))
local waiting_time=$((turnaround_time - burst_time[i]))
completed=$((completed + 1))
echo "P$i ${arrival_time[i]} ${burst_time[i]} $current_time
$turnaround_time $waiting_time"
else
current_time=$((current_time + time_quantum))
remaining_time[i]=$((remaining_time[i] - time_quantum))
fi
fi
done

if !$done; then
break
fi
done
}
# Call the Round Robin scheduling function
round_robin_scheduling "${arrival_time[*]}" "${burst_time[*]}" $time_quantum

Enter process names and burst times (comma-separated): P1,8 P2,6 P3,4
Process | Burst Time | Waiting Time | Turnaround Time
P0 | 8 | 0 | 2
P1 | 6 | 2 | 8
P2 | 4 | 8 | 12
P0 | 4 | 2 | 8
P1 | 2 | 8 | 10
P0 | 2 | 8 | 10
Average Waiting Time: 5.33
Average Turnaround Time: 8.67

You might also like