0% found this document useful (0 votes)
35 views12 pages

USP LAB Week 11 Programs

USP Lab

Uploaded by

srkakarlapudi
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)
35 views12 pages

USP LAB Week 11 Programs

USP Lab

Uploaded by

srkakarlapudi
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/ 12

USP LAB Week 11

Task: Greeting Based on Current Time


AIM

To write a shell script that greets the user with "Good Morning," "Good Afternoon," "Good
Evening," or "Good Night" based on the current time.

Description

This shell script uses the current hour of the system time to determine the appropriate
greeting message. The script reads the current hour using the date command and, based on
conditions, it prints the corresponding greeting.

 0 to 11 hours: "Good Morning!"


 12 to 16 hours: "Good Afternoon!"
 17 to 20 hours: "Good Evening!"
 21 to 23 hours: "Good Night!"

Key Concepts Used

1. Date Command:
o The date command with the +"%H" format extracts the current hour (in 24-
hour format).
2. Conditional Execution:
o if-elif-else statements are used to display different greetings based on the
current hour.
o Relational Operators (-ge, -lt) help determine the time range for each
greeting.
3. Shell Variables:
o The hour variable stores the current hour value.

Code
#!/bin/ksh

# Get the current hour in 24-hour format


hour=$(date +"%H")

# Conditional statements to determine the appropriate greeting


if [ $hour -ge 0 ] && [ $hour -lt 12 ]; then
echo "Good Morning!"
elif [ $hour -ge 12 ] && [ $hour -lt 17 ]; then
echo "Good Afternoon!"
elif [ $hour -ge 17 ] && [ $hour -lt 21 ]; then
echo "Good Evening!"
else
echo "Good Night!"
fi
Explanation of the Code

1. Reading the Current Hour:


o The date +"%H" command extracts the current hour in 24-hour format and
stores it in the hour variable.
2. Using if-elif-else Conditions:
o The if-elif-else block checks the value of hour:
 0 to 11: Displays "Good Morning!"
 12 to 16: Displays "Good Afternoon!"
 17 to 20: Displays "Good Evening!"
 21 to 23: Displays "Good Night!"
3. Output the Greeting:
o Depending on the time, the appropriate message is printed using the echo
command.

Output Examples

Example Run 1

Time: 10:30 AM

$ ./greeting.ksh
Good Morning!

Example Run 2

Time: 2:00 PM

$ ./greeting.ksh
Good Afternoon!

Example Run 3

Time: 7:15 PM

$ ./greeting.ksh
Good Evening!

Example Run 4

Time: 10:45 PM

$ ./greeting.ksh
Good Night!

Inferences

 The date command is a powerful tool for retrieving system time.


 Conditional statements allow the script to make decisions based on different time
ranges.
 The script provides a dynamic user experience by greeting the user appropriately at
any time of the day.

Task2: Binary Search in a Sorted Array


AIM

To write a shell script that performs a binary search on a sorted array to find the position of
a target element.

Description

This shell script allows the user to input a sorted array of elements and a target element to
search for. It implements the binary search algorithm to efficiently find the position of the
target element in the array. The script assumes that the array is sorted in ascending order.

Key Concepts Used

1. Input Handling:
o The script reads a sorted array from the user and the target element to search
for.
2. Positional Parameters:
o The input array is converted into positional parameters using set -- $input,
allowing easy access to array elements.
3. Binary Search Logic:
o Low and High Indices: Initial indices are set to track the search range.
o Looping Structure: A while loop continues until the low index is less than or
equal to the high index.
o Midpoint Calculation: The midpoint of the current search range is calculated
and compared with the target.
4. Error Handling:
o The script uses 2>/dev/null to suppress errors when comparing non-numeric
values.

Code
#!/bin/sh

# Prompt for sorted array input


echo "Enter the sorted array elements (space-separated):"
read input

# Prompt for the target element to search


echo "Enter the element to search for:"
read target

# Convert the input string into positional parameters


set -- $input
# Initialize low and high indices
low=1
high=$#

# Binary search logic (without functions)


while [ "$low" -le "$high" ]; do
mid=$(( (low + high) / 2 ))

# Get the middle element using positional parameters


mid_value=$(eval echo \$$mid)

# Ensure mid_value is numeric before comparison


if [ "$mid_value" -eq "$target" ] 2>/dev/null; then
echo "Element $target found at position $mid."
exit 0
elif [ "$mid_value" -lt "$target" ] 2>/dev/null; then
low=$((mid + 1))
else
high=$((mid - 1))
fi
done

echo "Element $target not found."

Explanation of the Code

1. Reading Inputs:
o The script prompts the user to enter the sorted array and the target element
to search for.
2. Setting Positional Parameters:
o The command set -- $input converts the input string into positional
parameters, allowing each element of the array to be accessed via $1, $2, etc.
3. Binary Search Logic:
o The script initializes low and high indices to define the search range.
o A while loop continues as long as low is less than or equal to high:
 The midpoint is calculated.
 The middle element is fetched using eval.
 The script compares the middle element with the target:
 If equal, the position is printed, and the script exits.
 If the middle element is less than the target, the low index is
updated.
 If the middle element is greater than the target, the high index
is updated.
4. Output Results:
o If the target element is found, its position is displayed. If not found, a message
indicates that the target is not in the array.

Output Examples

Example Run 1

$ ./binary_search.ksh
Enter the sorted array elements (space-separated):
1 2 3 4 5 6 7 8 9 10
Enter the element to search for:
5
Element 5 found at position 5.

Example Run 2

$ ./binary_search.ksh
Enter the sorted array elements (space-separated):
1 2 3 4 5 6 7 8 9 10
Enter the element to search for:
11
Element 11 not found.

Inferences

 The script effectively utilizes binary search, which significantly reduces the number
of comparisons required to find an element in a sorted array compared to linear
search.
 The handling of positional parameters demonstrates how to work with dynamic input
in shell scripts.

Task 3: Screen Lock and Unlock Script


AIM

To write a Korn shell (ksh) script that sets a password, locks the screen, and allows
unlocking only upon entering the correct password.

Description

This shell script demonstrates how to create a basic password-protected screen lock. The
user first sets a password to lock the screen. The screen remains locked until the correct
password is entered. The input is hidden while entering the password using stty -echo,
ensuring privacy. This script demonstrates basic input handling, looping, and conditional
logic.

Code
#!/bin/ksh

# Step 1: Set the password


echo "Set a password to lock the screen:"
stty -echo # Disable echo to hide the password input
read password
stty echo # Re-enable echo
echo "Password has been set. Screen is now locked."

# Step 2: Lock the screen until the correct password is entered


while true; do
echo "Enter the password to unlock the screen:"
stty -echo # Disable echo to hide the password input
read input
stty echo # Re-enable echo

if [ "$input" = "$password" ]; then


echo "Screen unlocked."
break # Exit the loop when the correct password is entered
else
echo "Incorrect password. Try again."
fi
done

Explanation of the Code

1. Setting the Password:


o The script prompts the user to set a password.
o stty -echo is used to disable terminal echo, ensuring the password input
remains hidden.
o After entering the password, stty echo re-enables input visibility.
2. Locking the Screen:
o The script enters a while loop that repeatedly prompts the user to enter the
password.
o If the entered password ($input) matches the previously set password
($password), the screen is unlocked, and the loop exits.
o If the password is incorrect, the user is asked to try again.
3. Password Verification and Exit:
o The script uses an if statement to compare the entered password with the
stored password.
o If they match, "Screen unlocked" is displayed, and the loop is terminated.
o If they do not match, an error message is displayed, and the loop continues.

Outputs

Example Run 1: Successful Unlock

$ ./screen_lock.ksh
Set a password to lock the screen:
<password input not displayed>
Password has been set. Screen is now locked.

Enter the password to unlock the screen:


<password input not displayed>
Screen unlocked.

Example Run 2: Incorrect Password Attempt

$ ./screen_lock.ksh
Set a password to lock the screen:
<password input not displayed>
Password has been set. Screen is now locked.

Enter the password to unlock the screen:


<password input not displayed>
Incorrect password. Try again.

Enter the password to unlock the screen:


<password input not displayed>
Screen unlocked.

Inferences

 Hiding password input using stty -echo ensures security during password entry.
 The while loop provides continuous prompts until the correct password is entered,
ensuring access control.
 Conditional statements allow the script to unlock the screen only if the correct
password is entered.
 This script demonstrates simple authentication logic and secure input handling
using Korn shell commands.

Task 4: Count Vowels, Consonants, Digits, Whitespaces, and


Special Characters in a String

AIM

To write a Korn shell (ksh) script that counts the number of vowels, consonants, digits,
whitespaces, and special characters in a given string.

Description

This shell script reads a string from the user and counts different types of characters within
the string. The grep command is used with appropriate regular expressions to extract each
character type, and wc -l is used to count the occurrences.

The task demonstrates string manipulation, pattern matching using grep, and counting
operations in a shell script.

Code

#!/bin/ksh

# Prompt the user to enter a string


echo "Enter a string:"
read str

# Count the number of vowels


vowels=$(echo $str | grep -o -i "[aeiou]" | wc -l)
# Count the number of consonants
consonants=$(echo $str | grep -o -i "[bcdfghjklmnpqrstvwxyz]" | wc -l)

# Count the number of digits


digits=$(echo $str | grep -o "[0-9]" | wc -l)

# Count the number of whitespaces


whitespaces=$(echo $str | grep -o "[[:space:]]" | wc -l)

# Count the number of special characters


special_chars=$(echo $str | grep -o "[^a-zA-Z0-9[:space:]]" | wc -l)

# Display the results


echo "Vowels: $vowels"
echo "Consonants: $consonants"
echo "Digits: $digits"
echo "Whitespaces: $whitespaces"
echo "Special Characters: $special_chars"

Explanation of the Code

1. Reading the Input String:


o The read command captures the user-inputted string and stores it in the
variable str.
2. Counting Vowels:
o The grep -o -i "[aeiou]" extracts all vowels (case-insensitive) from the
string, and wc -l counts the occurrences.
3. Counting Consonants:
o A similar pattern, "[bcdfghjklmnpqrstvwxyz]", is used to extract
consonants.
4. Counting Digits:
o The pattern [0-9] matches digits, and their count is determined using wc -l.
5. Counting Whitespaces:
o [[:space:]] matches spaces, tabs, or any whitespace characters.
6. Counting Special Characters:
oThe pattern [^a-zA-Z0-9[:space:]] matches any character other than
alphanumeric and space characters.
7. Displaying the Results:
o The echo command prints the counts for vowels, consonants, digits,
whitespaces, and special characters.

Outputs

Example Run 1

$ ./char_count.ksh
Enter a string:
Hello World! 123
Vowels: 3
Consonants: 7
Digits: 3
Whitespaces: 2
Special Characters: 1

Example Run 2
$ ./char_count.ksh
Enter a string:
#Ksh_Scripting_101!

Vowels: 3
Consonants: 11
Digits: 3
Whitespaces: 0
Special Characters: 3

Inferences

 This script efficiently processes the input string to count specific character types using
pattern matching.
 grep is used with various regular expressions to filter character types, and wc -l
gives the counts.
 The script demonstrates string manipulation techniques and basic regex operations
in shell scripting.

Task 5: Generate the Multiplication Table of a Given Number


AIM
To write a Korn shell (ksh) script that generates and displays the multiplication table for a
given number.
Description
This shell script prompts the user to enter a number and generates its multiplication table up
to 10. The task demonstrates the use of looping structures and arithmetic operations in
shell scripting.
Code

#!/bin/ksh

# Prompt the user to enter a number


echo "Enter a number:"
read number

# Display the header for the multiplication table


echo "Multiplication table for $number:"

# Loop to generate the multiplication table from 1 to 10


for i in {1..10}
do
# Calculate and display the result for each iteration
echo "$number x $i = $((number * i))"
done

Explanation of the Code


1. Reading the Input:
o The read command captures the user’s input number and stores it in the
number variable.
2. Displaying the Table Header:
o The echo command prints the title, indicating the multiplication table for the
entered number.
3. Using a Loop to Generate the Table:
o The for loop iterates from 1 to 10 to generate the multiplication table.
o In each iteration, $i takes the value of the current iteration step.
4. Performing Arithmetic Operations:
o Inside the loop, $((number * i)) calculates the product of the input number
and the current iteration value.
5. Displaying the Results:
o The echo command prints the multiplication operation and its result for each
iteration.
Outputs
Example Run 1
$ ./multiplication_table.ksh
Enter a number:
5
Multiplication table for 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Example Run 2
$ ./multiplication_table.ksh
Enter a number:
9
Multiplication table for 9:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Inferences
 This script effectively demonstrates the use of for loops to automate repetitive tasks.
 Arithmetic operations within a loop allow dynamic calculations for different inputs.
 The Korn shell provides easy ways to interact with users and handle arithmetic using
$(( )) for evaluation.

You might also like