0% found this document useful (0 votes)
29 views23 pages

Labprgms

The document contains a collection of shell scripts that perform various tasks, including printing prime numbers, reversing a number, calculating the sum of digits, implementing Linux commands, and managing files. Each script includes user prompts and error handling to ensure proper execution. The scripts cover a wide range of functionalities, from basic arithmetic to process management in Linux.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views23 pages

Labprgms

The document contains a collection of shell scripts that perform various tasks, including printing prime numbers, reversing a number, calculating the sum of digits, implementing Linux commands, and managing files. Each script includes user prompts and error handling to ensure proper execution. The scripts cover a wide range of functionalities, from basic arithmetic to process management in Linux.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

1.

Shell script to print all the prime numbers


between M to N (M<N).

#!/bin/bash
echo "Enter the value of M:"
read M
echo "Enter the value of N:"
read N
# Validate input
if [ $M -ge $N ]; then
echo "Invalid input. Make sure that M<N."
exit 1
fi
if [ $M -lt 2 ]; then
M=2 # Start from the first prime number if M is less
than 2
fi

echo "Prime numbers between $M and $N are:"

# Loop through each number from M to N


for (( num=M; num<=N; num++ )); do
prime=1 # Assume the number is prime

# Check for factors from 2 to the square


root of num
for (( i=2; i*i<=num; i++ )); do
if (( num % i == 0 )); then
prime=0 # Not a prime
number
break
fi
done
# If is_prime is still 1, then num is a
prime number
if (( prime == 1 )); then
echo $num
fi
done

2. Shell script to reverse a number and check


whether it is a palindrome.

#!/bin/bash
echo "Enter a number: "
read number

# Initialize variables
reverse=0
original=$number

# Reverse the number


while [ $number -gt 0 ]; do
remainder=$(( number % 10 )) # Get
the last digit
reverse=$(( reverse * 10 + remainder ))
# Build the reversed number
number=$(( number / 10 )) # Remove
the last digit from the original number
done

# Check if the original number is equal to the


reversed number
if [ $original -eq $reverse ]; then
echo "$original is a palindrome."
else
echo "$original is not a palindrome."
fi
3.Shell script to find the sum of digits of a
given number using loops and without using
loops.

#!/bin/bash

# Function to find Sum of digits (with loops)


sum_with_loop()
{
sum=0
# Calculate the sum of digits using a loop
while [ $number -gt 0 ]; do
digit=$(( number % 10 )) # Get the
last digit
sum=$(( sum + digit )) # Add the
digit to sum
number=$(( number / 10 )) # Remove
the last digit
done

echo "Sum of digits (using loops) is: $sum"


}

# Function to find Sum of digits (without loops)


sum_without_loop()
{
num=$1
if [ $num -lt 10 ]; then
echo $num
else
last_digit=$((num % 10))
remaining_number=$((num / 10))
sum=$((last_digit + $(sum_without_loop
$remaining_number)))
echo $sum
fi
}

# Prompt the user to enter a number


echo "Enter a number: "
read number
number_cpy=$number
sum_with_loop $number
sum2=$(sum_without_loop $number_cpy)
echo "Sum of digits (without using loops) is:
$sum2"

4.Shell script to implement any 10 linux


commands using case.

#!/bin/bash

# Function to display the menu and execute


commands based on user choice
while true; do
echo "Menu:"
echo "1) List files in the current directory
(ls)"
echo "2) Show current working directory
(pwd)"
echo "3) Display disk usage (df)"
echo "4) Display current date and time"
echo "5) Create a new directory (mkdir)"
echo "6) Copy a file (cp)"
echo "7) Show system information
(uname)"
echo "8) Show file contents (cat)"
echo "9) Show the Current Month's
Calendar (cal)"
echo "10) Exit"
read -p "Choose an option (1-10): "
choice

case $choice in
1)
ls -l # Lists files in the
current directory with details
;;
2)
pwd # Prints the current
working directory
;;
3)
df -h # Displays disk space
usage in a human-readable format
;;
4)
date # Displays the current
date and time
;;
5)
read -p "Enter directory name
to create: " dirname
mkdir "$dirname" # Creates a
new directory
;;
6)
read -p "Enter source file to
copy: " sourcefile
read -p "Enter destination
filename: " destfile
cp "$sourcefile" "$destfile" #
Copies a file
;;
7)
uname -a
;;
8)
read -p "Enter filename to
display: " filename
cat "$filename" # Displays
contents of the specified file
;;
9)
cal # Displays the current
month's calendar
;;
10)
echo "Exiting..."
exit 0 # Exits the script
;;
*)
echo "Invalid option, please
try again." # Handles invalid input
;;
esac

# Wait for user input before clearing the


screen and showing the menu again
read -p "Press [Enter] to continue..."
clear
done
5.Shell script that displays list of all the files in
the current directory to which the user has
read, write and execute permissions.

#!/bin/bash
# Display a message indicating the start of the
process
echo "Files with read, write, and execute
permissions:"

# Loop through all files in the current directory


for file in *; do
# Check if it is a file and if it has
read, write, and execute permissions
if [ -f "$file" ] && [ -r "$file" ] && [ -
w "$file" ] && [ -x "$file" ]; then
echo "$file" # Print the file name
if it meets the criteria
fi
done
6.Shell script to copy a file within current
directory.

#!/bin/bash
# Prompt the user for the name of the file to
copy
echo "Enter the name of the file to copy:"
read source_file
# Check if the source file exists
if [ ! -f "$source_file" ]; then
echo "File '$source_file' does not exist."
exit 1
fi

# Prompt the user for the name of the new


file
echo "Enter the name for the new copy:"
read destination_file

# Copy the file using cp command


cp "$source_file" "$destination_file"

# Check if the copy was successful


if [ $? -eq 0 ]; then
echo "File '$source_file' has been copied
to '$destination_file'."
else
echo "Failed to copy '$source_file'."
fi
7.Shell script to copy file between two
directories.

#!/bin/bash
# Prompt the user for the source file path
echo "Enter the name of the file to copy:"
read source_file

# Check if the source file exists


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

# Prompt the user for the destination directory


echo "Enter the destination directory:"
read destination_dir

# Check if the destination directory exists


if [ ! -d "$destination_dir" ]; then
echo "Error: Directory '$destination_dir' does
not exist."
exit 1
fi
# Copy the file to the destination directory
cp "$source_file" "$destination_dir"

# Check if the copy was successful


if [ $? -eq 0 ]; then
echo "File '$source_file' has been copied
to '$destination_dir'."
else
echo "Failed to copy '$source_file'."
fi

8.Shell script to create two data files and


compare them to display unique and common
entries.

#!/bin/bash
# Create two data files with sample entries
echo "Creating data files..."
# Create first data file
cat <<EOL > file1.txt
apple
banana
cherry
date
papaya
grape
EOL

# Create second data file


cat <<EOL > file2.txt
banana
cherry
date
kiwi
lemon
mango
papaya
EOL

echo "Data files created: file1.txt and file2.txt"

# Sort the files before comparison (comm


requires sorted input)
sort file1.txt -o file1.txt
sort file2.txt -o file2.txt

# Compare the two files and display unique


and common entries
echo "Comparing files for unique and common
entries..."
echo "uniq_file1 uniq_file2 common_entries"
comm file1.txt file2.txt

9.Shell script to count the number of vowels in


a string.

#!/bin/bash
# Prompt the user for a string input
read -p "Enter a string: " input_string

# Initialize vowel count to zero


vowel_count=0

# Loop through each character in the input


string
for (( i=0; i<${#input_string}; i++ )); do
char="${input_string:i:1}" # Extract each
character

# Check if the character is a vowel


(case insensitive)
if [[ "$char" =~ [aeiouAEIOU] ]]; then
((vowel_count++)) # Increment the
vowel count
fi
done

# Display the total number of vowels found


echo "Number of vowels in the string:
$vowel_count"

10.Shell script to convert uppercase to lowercase


and viceversa.
#!/bin/bash
# Prompt the user to enter a string
read -p "Enter a string: " input_string

# Convert uppercase to lowercase and lowercase


to uppercase
converted_string=$(echo "$input_string" | tr
'[:upper:][:lower:]' '[:lower:][:upper:]')

# Display the original and converted strings


echo "Original string: $input_string"
echo "Converted string: $converted_string"
11.Shell script to accept a word and perform
pattern matching in a given file.

#!/bin/bash
# Prompt the user for the word to search
read -p "Enter a word to search for: "
search_word

# Prompt the user for the file to search in


read -p "Enter the filename to search in: "
filename

# Check if the file exists


if [ ! -f "$filename" ]; then
echo "Error: File '$filename' does not
exist."
exit 1
fi
# Perform pattern matching using grep
echo "Searching for '$search_word' in '$filename':"
grep -n "$search_word" "$filename"

# Check if grep found any matches


if [ $? -eq 0 ]; then
echo "Search completed."
else
echo "No matches found for
'$search_word'."
fi
12.Shell script to find factorial of a number.

#!/bin/bash
# Prompt the user to enter a number
read -p "Enter a number: " num

# Initialize factorial variable


fact=1

# Calculate factorial using a for loop


for ((i=1; i<=num; i++)); do
fact=$((fact * i)) # Multiply fact by i
done

# Display the result


echo "Factorial of $num is: $fact"
13.Write a menu driven program to demonstrate
zombie and orphan process.

#!/bin/bash
# Function to create a zombie process
create_zombie() {
echo "Creating a child Process..."
# Create a child process
(
# Child process sleeps for 3
seconds
sleep 3
echo "Child process completed."
echo "I am a Zombie while the
parent sleeps."
) &

# Parent process sleeps for 30 seconds


to ensure child becomes a zombie
echo "Parent process is now sleeping for
30 seconds."
sleep 20
echo "Parent process has finished and is
back."
echo "Child is no longer a Zombie."
}

# Function to create an orphan process


create_orphan() {
echo "Creating an Orphan Process..."
# Create a child process
(
echo "Child Process created."
sleep 10 # Child process sleeps for
10 seconds
echo "Child process completed
execution. Now i will exit."
) &

# Parent process exits immediately


echo "Parent process exiting early. The
child will become an orphan."
exit
}

# Main menu loop


while true; do
echo "Menu:"
echo "1) Create Zombie Process"
echo "2) Create Orphan Process"
echo "3) Exit"

read -p "Choose an option: " choice


case $choice in
1)
create_zombie
;;
2)
create_orphan
;;
3)
echo "Exiting..."
exit 0
;;
*)
echo "Invalid option, please
try again."
;;
esac

read -p "Press [Enter] to continue..."


done

You might also like