0% found this document useful (0 votes)
61 views19 pages

Shell Programming Examples and Scripts

The document contains a series of shell programming exercises aimed at performing various tasks, including arithmetic operations, generating patterns, reversing numbers, and checking for palindromes. It also includes scripts for generating Fibonacci numbers, printing system information, calculating factorial sums, and greeting users based on the time of day. Each exercise is accompanied by code snippets and expected outputs.

Uploaded by

aswanrajakrishna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views19 pages

Shell Programming Examples and Scripts

The document contains a series of shell programming exercises aimed at performing various tasks, including arithmetic operations, generating patterns, reversing numbers, and checking for palindromes. It also includes scripts for generating Fibonacci numbers, printing system information, calculating factorial sums, and greeting users based on the time of day. Each exercise is accompanied by code snippets and expected outputs.

Uploaded by

aswanrajakrishna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OS Lab Shell Programs

Aswanrajakrishna S S
23BCE2111

1. Write a Shell program to perform all arithmetic


operations using case statement

Code:
echo "Enter the numbers:"
read a
read b
echo "[Link] [Link] [Link] [Link]"
read o
case $o in
1) ((c =a+b)); echo $c;;
2) ((c =a-b)); echo $c;;
3) ((c =a*b)); echo $c;;
4) ((c =a/b)); echo $c;;
*)echo "Invalid Option"
esac
Output:
2. Write a Shell program to read 'n' and generate a pattern
given below. 1 1 2 1 2 3 1 2 3 4
Code:
echo "Enter the number to print the pattern"
read n
for((i=1;i<=n;i++))
do
for((j=1;j<=i;j++))
do
echo -n "$j "
done
echo ""
done
Output:
3. Write a script to print a given number in reverse order.
Requirements: • Read a multi-digit number from user and
reverse the number. • It’s not just printing in reverse order
• You have to extract each digit and convert to reverse. •
When ‘0’ comes as last digit, discard while reversing.
Code:
echo "Enter the multi Digit Number"
read m
while((m!=0))
do
((n =m%10))
echo -n "$n"
((m =m/10))
done

Output:
4. Write a Shell program to read 'n' and generate Fibonacci
numbers less than or equal to n. Requirements: •
Remember n is not number of elements to print • It’s the
boundary of elements to print.
Code:
echo "Enter the limit to generate fibbo Series"
read n
m=0
o=1
echo "Fibbo Series:-"
while((m<=n))
do
echo -n "$m "
((p=m+o))
((m=o))
((o=p))
done
Output:
5. Write a Shell program to check whether the given string is
palindrome or not.
Code:
echo "Enter the string to check its Palindrom check"
read str
arr=($(echo "$str" | grep -o .))
len=${#arr[@]}
check=0
for((i=0;i<len/2;i++))
do
if [ "${arr[i]}" = "${arr[len-i-1]}" ]
then
((check++))
fi
done
if((check==len/2))
then
echo "Yes"
else
echo "No"
fi
Output:
6. Write a script to print the length of each and every string
using arrays. Prerequisites: • Knowledge about arrays. •
How to find length of string. Requirements: • Print all the
string lengths one-by-one. • Number of argument may
vary.
Code:
echo "Enter the String to find its length"
read n
arr=($(echo "$n" | grep -o .))
len=${#arr[@]}
echo "The Length of the $len"
Output:
7. Write a script to print the following system information. i)
Currently logged users ii) Your shell directory iii) Home
directory iv) OS name & version v) Current working
directory vi) Number of users logged in vii)Show all
available shells in your system viii) Hard disk information
ix) CPU information x) Memory information xi) File system
information xii)Currently running process
Code:
display_menu() {
clear
echo "========================================="
echo " System Information Script"
echo "========================================="
echo "What would you like to know about your system?"
echo "-----------------------------------------"
echo "1) Who's logged in right now?"
echo "2) Where is my current shell located?"
echo "3) Where is my home directory?"
echo "4) What's the OS name and version?"
echo "5) Where am I right now? (Current working directory)"
echo "6) How many users are logged in?"
echo "7) What shells are available on this system?"
echo "8) Tell me about the hard disk"
echo "9) Tell me about the CPU"
echo "10) Tell me about the memory (RAM)"
echo "11) Tell me about the file systems"
echo "12) What processes are currently running?"
echo "-----------------------------------------"
echo "13) Exit"
echo "========================================="
echo -n "Enter your choice: "
}

while true; do
display_menu
read choice

case $choice in
1)
echo "--- Currently logged users: ---"
who
;;
2)
echo "--- Your shell directory: ---"
echo $SHELL
;;
3)
echo "--- Your home directory: ---"
echo $HOME
;;
4)
echo "--- OS name and version: ---"
uname -a
;;
5)
echo "--- Current working directory: ---"
pwd
;;
6)
echo "--- Number of users logged in: ---"
who | wc -l
;;
7)
echo "--- Available shells: ---"
cat /etc/shells
;;
8)
echo "--- Hard disk information: ---"
lsblk
;;
9)
echo "--- CPU information: ---"
lscpu
;;
10)
echo "--- Memory information: ---"
free -h
;;
11)
echo "--- File system information: ---"
df -hT
;;
12)
echo "Exiting script. See you next time!"
exit 0
;;
*)
echo "That's not a valid option. Please choose a number from 1 to 13."
;;
esac

echo "-----------------------------------------"
read -p "Press Enter to return to the menu..."
done
Output:
8. Write a shell program to perform the following.
a) 1!+2!+3!+…+n!.
b) 1+x+x2+x3+…xn
c) 1+1/2! + 1/3! +1/4! + . .. . . . . 1/n!
Code:
a)
echo "Only for First Equation"
read n
for((i=1;i<=n;i++))
do
((arr[i]=1))
for((j=1;j<=i;j++))
do
((arr[i]=j*arr[i]))
done
done
for((i=1;i<=n;i++))
do
((sum =sum+arr[i]))
done
echo "The sum is $sum"
b)
echo "Enter a number n:"
read n
sum_expression=""
for (( i=1; i<=n; i++ )); do
if [ $i -eq 1 ]; then
sum_expression="x^$i"
else
sum_expression="$sum_expression + x^$i"
fi
done
echo "The expression is: $sum_expression"

c)
read n
sum=0
for((i=1;i<=n;i++))
do
((temp=1))
for((j=1;j<=i;j++))
do
#((arr[i]=j*arr[i]))
((temp= j*temp))

done
arr[i]=$(echo "scale=5; 1.0/$temp" | bc -l)
echo -n "${arr[i]} "
done
for((i=1;i<=n;i++))
do
sum=$(echo "scale=5; $sum + ${arr[i]}" |bc -l)
done
echo "The expression for this is $sum"
Output:
a)

b)

c)
[Link] script to print greetings based on time. Objective: •
Using time in script • Understanding bash configuration
files. Requirements: • The script should run as soon as you
log-on to system • Print greetings based on time as follows. •
“Good morning” (5 AM – 12 PM) • “Good noon” (12 PM – 1
PM) • “Good afternoon” (2 PM – 5 PM) • “Good evening” (5PM
– 9 PM) • “Good night” (9 PM – 5 AM)
Code:
current_hour=$(date +%H)
echo "$current_hour"
case $current_hour in
05|06|07|08|09|10|11)
echo "Good morning!"
;;
12)
echo "Good noon!"
;;
14|15|16)
echo "Good afternoon!"
;;
17|18|19|20)
echo "Good evening!"
;;
21|22|23|00|01|02|03|04)
echo "Good night!"
;;
esac
Output:
10. Write a Shell Program to fond the biggest and
smallest among three numbers
Code:
echo "Enter the Three Numbers :"
for((i=0;i<3;i++))
do
read arr[i]
done
((max = arr[0] ))
(( min = arr[0] ))
for((i=0;i<3;i++))
do
if((max<arr[i]))
then
((max = arr[i] ))
fi
if((min>arr[i]))
then
((min = arr[i] ))
fi
done
echo -e "The Maximum of three numbers is $max \nThe Minimum of three
numbers is $min"
Output:

Common questions

Powered by AI

The shell script first initializes the maximum and minimum values to the first number in the input list. It then iterates through the list, comparing each number with the current maximum and minimum, updating these accordingly. This straightforward comparison approach allows it to efficiently determine both extreme values within linear time, O(n), for three constants .

The greeting script retrieves the current hour using a date command and determines the message by matching the hour against predefined time ranges through a case statement. These ranges correspond to different parts of the day, such as morning, afternoon, and night. Based on the match, the appropriate greeting is displayed, ensuring that greetings are appropriately reflective of the time of day .

The script initializes two variables to represent the first two Fibonacci numbers, 0 and 1. Using a while loop, it then iteratively adds these numbers to calculate the next Fibonacci number, updating the variables accordingly, until the currently calculated number exceeds the given limit. The script outputs each number as it is calculated, as long as it meets the condition of being less than or equal to the specified boundary .

The shell script employs a loop to extract and print the least significant digit of a number using the modulus operation, then removes the extracted digit by integer division. This process is repeated until the number is zero. Leading zeros are naturally managed since they do not affect the integer division or modulus operations. By not storing any zeros that result directly from these operations, the script avoids erroneous leading zeros in the output .

The system information retrieval script presents options using a menu interface. It clears the screen and then displays a structured list of informational queries, each prefixed with a sequential number. Users are prompted to enter their choice, which the script handles using a case statement to perform the corresponding system command or retrieve information such as logged users, shell directory, OS details, and more. Invalid choices prompt a reminder to select a valid option .

The script splits the input string into individual characters stored in an array. It then utilizes the array's property to determine its total length, thus deducing the string length. This method leverages the abstraction provided by arrays to avoid explicitly counting characters, simplifying the logic and freeing the script from manually managing index counters. It benefits from the shell's native operations on arrays that ensure efficiency and simplicity .

Shell scripts provide automation, repeatability, and simplicity, allowing easy execution of complex tasks with minimal manual intervention. They harness existing command-line utilities, making them powerful for varied administration tasks without additional installations. However, they are limited by the scripting environment's capabilities, potentially facing performance bottlenecks and less error handling compared to more robust programming languages. Security vulnerabilities may arise from improper handling of inputs or environment configs .

The shell script first converts the string into an array of characters and calculates its length. It then checks the symmetry by comparing each character with its counterpart from the end towards the beginning. If all corresponding pairs of characters are equal, the string is identified as a palindrome; otherwise, it is not. This comparison is done only up to the midpoint of the string to reduce computational complexity .

The script uses nested loops where the outer loop iterates over each number for which the factorial is needed, and the inner loop calculates the factorial of the current number by iteratively multiplying the numbers. These factorials are stored in an array for easy summation later. This method efficiently handles factorial computation by breaking it down into repeated multiplication, minimizing the risk of recalculation and leveraging stored values for direct summation .

The shell program uses a case statement to handle different arithmetic operations by matching a user's input to a specific operation type (addition, subtraction, multiplication, division). When a user selects an option, the corresponding mathematical operation is performed on two user-provided numbers through arithmetic expansion. This approach simplifies code maintenance and enhances readability by consolidating multiple operations within a single conditional structure .

You might also like