0% found this document useful (0 votes)
22 views18 pages

163 OS Week-3

The document outlines a series of shell scripting assignments aimed at teaching various scripting techniques, including file information retrieval, pattern generation, largest number comparison, number reversal, password generation, directory content listing, user ID counting, executable file counting, and Fibonacci number generation. Each assignment includes a clear aim, description, and example code to illustrate the concepts being taught. The document serves as a comprehensive guide for students to practice and enhance their shell scripting skills.

Uploaded by

yeruvamokshitha
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)
22 views18 pages

163 OS Week-3

The document outlines a series of shell scripting assignments aimed at teaching various scripting techniques, including file information retrieval, pattern generation, largest number comparison, number reversal, password generation, directory content listing, user ID counting, executable file counting, and Fibonacci number generation. Each assignment includes a clear aim, description, and example code to illustrate the concepts being taught. The document serves as a comprehensive guide for students to practice and enhance their shell scripting skills.

Uploaded by

yeruvamokshitha
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
You are on page 1/ 18

Roll No:160122733163 Exp. No:…3.

… Date:……21/08/2024……

OPERATING SYSTEMS
ASSIGNMENT-3
1.AIM : Write a shell script for printing all file related information (i.e. size, permissions etc.)
Description :

Shebang (#!/bin/bash): Indicates the script should be run using Bash.

Loop (for file in *): Iterates over each file in the current directory.

File Check (if [ -e "$file" ]): Verifies if the file exists.

File Information:

• stat -c%s "$file": Prints file size in bytes.


• stat -c%A "$file": Prints file permissions.
• stat -c%U "$file": Prints file owner.
• stat -c%G "$file": Prints file group.
• stat -c%y "$file": Prints last modification time.

CODE :

#!/bin/bash

if [ "$(ls -A .)" ]; then

for file in *; do

if [ -f "$file" ]; then

echo "File: $file"

echo "---------------------------------"

echo "Size: $(stat -c%s "$file") bytes"

echo "Permissions: $(stat -c%A "$file")"

echo "Last Modified: $(stat -c%y "$file")"

echo "Owner: $(stat -c%U "$file")"

echo "Group: $(stat -c%G "$file")"

echo ""

fi

34
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

done

else

echo "No files found in the current directory."

Fi

OUTPUT :

2. AIM : Write a shell script that read a number and generate a pattern given below:

12

123

1234

Description :

Shebang (#!/bin/bash): Specifies that the script should be executed using Bash.

Prompt for Input:

• · echo -n "Enter a number: ": Prompts the user to enter a number without a newline.
• read number: Reads the user's input and stores it in the variable number.

Generate Pattern:

• · for ((i=1; i<=number; i++)): Outer loop that iterates from 1 to the user-provided
number.
• for ((j=1; j<=i; j++)): Inner loop that iterates from 1 to the current value of i, printing
numbers in a row.

35
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

• echo -n "$j ": Prints each number followed by a space on the same line.
• echo: Moves to the next line after printing the row of numbers.

CODE :

#!/bin/bash

echo -n "Enter a number: "

read number

for ((i=1; i<=number; i++))

do

for ((j=1; j<=i; j++))

do

echo -n "$j "

done

echo

done

OUTPUT :

3. AIM : Write a shell script to compare larger integer values from ‘n’ number of arguments
using command line arguments.

Description :

Argument Check:

• if [ $# -eq 0 ]; then: Checks if no arguments were provided.


• echo "Error: No arguments provided.": Prints an error message.
• echo "Usage: ./largest_number.sh num1 num2 num3 ...": Shows how to use the script.
• exit 1: Exits the script with an error code.

36
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

Initialize:

• largest=$1: Sets the first argument as the initial largest number.

Find the Largest Number:

• for num in "$@": Loops through all provided arguments.


• if [ "$num" -gt "$largest" ]; then: Compares each argument with the current largest
number.
• largest=$num: Updates largest if the current argument is greater.

CODE:

#!/bin/bash

if [ $# -eq 0 ]; then

echo "Error: No arguments provided."

echo "Usage: ./largest_number.sh num1 num2 num3 ..."

exit 1

fi

largest=$1

for num in "$@"

do

if [ "$num" -gt "$largest" ]; then

largest=$num

fi

done

echo "The largest number is: $largest"

OUTPUT :

37
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

4. AIM: Write a shell script that prints a given number in reverse order.

Description :

Argument Check:

• if [ $# -eq 0 ]; then: Checks if no arguments were provided.


• echo "Error: No number provided.": Prints an error message.
• echo "Usage: ./reverse_number.sh <number>": Shows how to use the script.
• exit 1: Exits the script with an error code.

Read Input:

• number=$1: Stores the provided number (argument) in the number variable.


• reverse=0: Initializes the reverse variable to 0 for storing the reversed number.

Reverse the Number:

• while [ $number -ne 0 ]: Loops while there are digits remaining in the number.
• digit=$(( number % 10 )): Extracts the last digit of the number.
• reverse=$(( reverse * 10 + digit )): Appends the digit to the reversed number.
• number=$(( number / 10 )): Removes the last digit from the number.

CODE :

#!/bin/bash

if [ $# -eq 0 ]; then

echo "Error: No number provided."

echo "Usage: ./reverse_number.sh <number>"

exit 1

fi

number=$1

reverse=0

while [ $number -ne 0 ]

do

digit=$(( number % 10 ))

reverse=$(( reverse * 10 + digit ))

38
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

number=$(( number / 10 ))

done

echo "Reversed Number: $reverse"

OUTPUT :

5. AIM : Write a shell script for generating random 8-character password including alpha
numeric characters.

Description :

•/dev/urandom: This is a special file that generates random data. It’s often used for
generating random numbers or strings.

· tr -dc 'A-Za-z0-9!@#$%^&*()_+{}[]:;<>?': The tr command is used to translate or delete


characters. The -dc option deletes all characters except those specified within the quotes. In
this case, it keeps only alphanumeric characters and a selection of special characters.

· head -c 8: The head command outputs the first part of files. The -c 8 option restricts the
output to the first 8 characters.

·Piping: The | (pipe) operator is used to pass the output of one command as input to another.
Here, the random data generated by /dev/urandom is passed through tr, and the resulting
string is trimmed to 8 characters by head.

CODE :

#!/bin/bash

password=$(tr -dc 'A-Za-z0-9!@#$%^&*()_+{}[]:;<>?' < /dev/urandom | head -c 8)

echo "Generated Password: $password"

OUTPUT :

39
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

6. AIM :Write a shell script that takes any number of directories as command-line arguments
and then lists the contents of each of these directories.

Description :

· Function list_directory_contents: This function takes a directory path as an argument and


lists its contents. The basename command is used to print just the file or directory name
without the path.

· Check for Arguments (if [ $# -eq 0 ]; then): If no arguments are passed, the script lists the
contents of the current directory (".").

· Loop Through Directories (for dir in "$@"; do): If arguments are provided, the script
loops through each one.

· Check if Directory Exists (if [ -d "$dir" ]; then): The script checks whether each argument
is a valid directory. If it is, it lists the contents; if not, it prints an error message.

· Listing Contents Without Using ls: The script avoids using the ls command and instead
relies on a loop to iterate through the contents of the directory.

CODE:

#!/bin/bash

list_directory_contents() {

for item in "$1"/*; do

if [ -e "$item" ]; then

echo "$(basename "$item")"

fi

done

if [ $# -eq 0 ]; then

echo "Contents of current directory:"

list_directory_contents "."

else

for dir in "$@"; do

if [ -d "$dir" ]; then

40
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

echo "Contents of directory '$dir':"

list_directory_contents "$dir"

echo

else

echo "Error: '$dir' is not a directory."

fi

done

fi

OUTPUT:

7. AIM : Write a shell to count the number of users with user IDs between 500 and 100000
on the system.

Description :

Default UID Range: The script initializes the default min_uid to 500 and max_uid to 10000.
These are standard ranges for regular user accounts on many Linux systems.

· Command Line Arguments: The script checks if custom min_uid and max_uid values are
provided as command-line arguments. If two arguments are provided, it updates the range.

· Reading /etc/passwd: The script reads each line of the /etc/passwd file. The IFS=: read -r
username _ uid _ splits each line by the : character, assigning the username to $username and
the UID to $uid. Other fields are ignored.

· UID Check: For each user, the script checks if the UID falls within the specified range. If it
does, the username and UID are printed, and the count is incremented.

· Counting Users: The script keeps track of how many users fall within the specified range
and prints the total at the end.

CODE :

41
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

#!/bin/bash

min_uid=500

max_uid=10000

if [ $# -ge 2 ]; then

min_uid=$1

max_uid=$2

elif [ $# -eq 1 ]; then

echo "Error: Please provide both minimum and maximum UID values."

exit 1

fi

user_count=0

while IFS=: read -r username _ uid _; do

if [ "$uid" -ge "$min_uid" ] && [ "$uid" -le "$max_uid" ]; then

echo "Username: $username, UID: $uid"

user_count=$((user_count + 1))

fi

done < /etc/passwd

echo "Total number of users with UID between $min_uid and $max_uid: $user_count"

OUTPUT:

42
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

8. AIM : For each directory in the $PATH, display the number of executable files in that
directory.

Description:

· IFS=':' read -ra directories <<< "$PATH":

The $PATH environment variable contains a colon-separated list of directories where


executable files are stored.

• IFS=':' sets the Internal Field Separator to a colon, so that read splits the $PATH
string into an array of directories.

· Loop Through Directories:

• · The script loops through each directory stored in the directories array.

· Check If Directory Exists ([ -d "$dir" ]):

• · Before processing, the script checks whether each directory in $PATH actually
exists. This avoids errors if the directory does not exist.

· Check for Executable Files:

• · The script loops through each file in the directory ("$dir"/*) and checks if it is both
a regular file ([ -f "$file" ]) and executable ([ -x "$file" ]).

· Count Executable Files:

• · If a file is executable, it increments the executable_count for that directory.

· Print Directory and Executable Count:

• · After counting the executables in a directory, the script prints the directory name
and the number of executable files found.

· Accumulate Total Executables:

• · The count of executables from each directory is added to the total_executables


variable.

· Total Executable Files:

• · Finally, the script prints the total number of executable files across all directories in
the $PATH.

43
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

CODE :

#!/bin/bash

total_executables=0

IFS=':' read -ra directories <<< "$PATH"

for dir in "${directories[@]}"; do

if [ -d "$dir" ]; then

executable_count=0

for file in "$dir"/*; do

if [ -f "$file" ] && [ -x "$file" ]; then

executable_count=$((executable_count + 1))

fi

done

echo "Directory: $dir"

echo "Executable files: $executable_count"

Echo

total_executables=$((total_executables + executable_count))

else

echo "Warning: $dir is not a valid directory."

fi

done

echo "Total number of executable files: $total_executables"

44
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

OUTPUT:

9. AIM : Write a shell script to generate Fibonacci numbers less than or equal to a given
number ‘n’.

Description :

· Function Definition (generate_fibonacci):

• · limit: The maximum value for Fibonacci numbers.


• a and b: Initial values of Fibonacci sequence.
• Use a while loop to print numbers as long as a is less than or equal to limit.

· Argument Handling:

• · The script expects exactly one argument (the boundary number n).
• It checks if the argument is a positive integer.

· Calling the Function:

• · generate_fibonacci $1 is called with the boundary number n.

CODE :

#!/bin/bash

generate_fibonacci() {

local limit=$1

local a=0

local b=1

echo "Fibonacci numbers less than or equal to $limit:"

while [ $a -le $limit ]; do

45
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

echo $a

local temp=$a

a=$b

b=$((temp + b))

done

if [ $# -ne 1 ]; then

echo "Usage: $0 <number>"

exit 1

fi

if ! [[ $1 =~ ^[0-9]+$ ]]; then

echo "Error: Input must be a positive integer."

exit 1

fi

generate_fibonacci $1

OUTPUT:

10.AIM : Write a shell script to print the following system information:

a) Currently logged users

b) Your shell script

c) Home directory

d) OS name and version

46
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

e) Current working directory

f) Number of users logged in

g) Show all available shells in your system

h) Hard disk information

i) CPU information

j) Memory information

k) File system information

l) Currently running processes

Description :

· Functions:

• Each function corresponds to a specific piece of system information.


• Commands used include who, cat, pwd, uname, df, lscpu, free, ps, and reading from
/etc/shells.

· Menu Function (show_menu):

• Displays options for the user to choose from.

· Main Loop:

• Displays the menu and reads the user's choice.


• Executes the appropriate function based on the user's selection.

· Execution:

• Save the script to a file, e.g., system_info.sh, make it executable with chmod +x
system_info.sh, and run it with ./system_info.sh.

CODE :

#!/bin/bash

display_logged_users() {

echo "Currently logged in users:"

who

47
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

display_script() {

echo "Your shell script:"

cat "$0"

display_home_directory() {

echo "Home directory:"

echo "$HOME"

display_os_info() {

echo "OS name and version:"

uname -a

display_cwd() {

echo "Current working directory:"

pwd

display_user_count() {

echo "Number of users logged in:"

who | wc -l

display_shells() {

echo "Available shells in the system:"

cat /etc/shells

48
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

display_disk_info() {

echo "Hard disk information:"

df -h

display_cpu_info() {

echo "CPU information:"

lscpu

display_memory_info() {

echo "Memory information:"

free -h

display_fs_info() {

echo "File system information:"

df -T

display_processes() {

echo "Currently running processes:"

ps aux

show_menu() {

clear

echo "System Information Menu"

echo "1) Currently logged users"

49
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

echo "2) Your shell script"

echo "3) Home directory"

echo "4) OS name and version"

echo "5) Current working directory"

echo "6) Number of users logged in"

echo "7) Show all available shells in your system"

echo "8) Hard disk information"

echo "9) CPU information"

echo "10) Memory information"

echo "11) File system information"

echo "12) Currently running processes"

echo "0) Exit"

echo -n "Enter your choice [0-12]: "

while true; do

show_menu

read choice

case $choice in

1) display_logged_users ;;

2) display_script ;;

3) display_home_directory ;;

4) display_os_info ;;

5) display_cwd ;;

6) display_user_count ;;

50
Page No …………………. Signature of the Faculty………………………...
Roll No:160122733163 Exp. No:…3.… Date:……21/08/2024……

7) display_shells ;;

8) display_disk_info ;;

9) display_cpu_info ;;

10) display_memory_info ;;

11) display_fs_info ;;

12) display_processes ;;

0) exit 0 ;;

*) echo "Invalid choice. Please enter a number between 0 and 12." ;;

esac

echo

Done

OUTPUT :

51
Page No …………………. Signature of the Faculty………………………...

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy