0% found this document useful (0 votes)
1 views

linux lab

This document is a practical file for a course on Operating Systems and Linux, submitted by a BCA student at Uttaranchal University. It includes a series of shell script exercises that cover various topics such as directory creation, file permission checks, finding the largest number, and file handling operations. Each practical exercise is accompanied by code snippets and expected outputs.

Uploaded by

ritika4404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

linux lab

This document is a practical file for a course on Operating Systems and Linux, submitted by a BCA student at Uttaranchal University. It includes a series of shell script exercises that cover various topics such as directory creation, file permission checks, finding the largest number, and file handling operations. Each practical exercise is accompanied by code snippets and expected outputs.

Uploaded by

ritika4404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PRACTICAL FILE

OF
“OPERATING SYSTEM AND LINNUX ”

Submitted in the Partial Fulfilment for the Award of Degree

BACHELOR OF COMPUTER
APPLICATIONS

UTTARANCHAL UNIVERSITY
(Session:2024-2025)

Under the Supervision of Submitted By


Mrs. Divya Pandey Shruti rawat
Assistant professor Uttaranchal School of Computing BCA (VI)Semester

Sciences (USCS) Roll Num: - 15

1
PRACTICAL – 01.
Design, and implement a shell script that accepts a path name and creates all the components
in the path name as directories (ex:a/b/c/d should creates a directory a,a/b,a/b/c,a/b/c/d.)

#!/bin/bash

# Accept path name from user


echo "Enter the path name:"
read path

# Create directories
mkdir -p "$path"

# Check if creation was successful


if [ $? -eq 0 ]; then
echo "Directories created successfully: $path"
else
echo "Failed to create directories!"
fi

OUTPUT:

2
PRACTICAL – 02.

Design, develop and implement a shell script that accepts two file names as arguments checks
if the permissions for these files are identical and if the permissions are identical, output
common permissions and otherwise output each file name followed by its permissions.

# Check if exactly two arguments are provided


if [ $# -ne 2 ]; then
echo "Usage: $0 <file1> <file2>"
exit 1
fi

file1=$1
file2=$2

# Check if both files exist


if [ ! -e "$file1" ] || [ ! -e "$file2" ]; then
echo "One or both files do not exist."
exit 1
fi

# Get the permissions of both files


perm1=$(stat -c "%A" "$file1")
perm2=$(stat -c "%A" "$file2")

# Compare permissions
if [ "$perm1" = "$perm2" ]; then
echo "Common Permissions: $perm1"
else
echo "$file1: $perm1"
echo "$file2: $perm2"
fi

OUTPUT:
Case 1: Identical permissions

Case 2: Different permissions

3
PRACTICAL – 03.

Design, develop and implement a shell script to find out biggest number from given three
nos. Numbers are supplied as command line arguments. Print error if sufficient arguments are
not supplied.

#!/bin/bash

# Check if exactly 3 arguments are passed


if [ $# -ne 3 ]; then
echo "Error: Please supply exactly 3 numbers as arguments."
echo "Usage: $0 num1 num2 num3"
exit 1
fi

# Assign command line arguments to variables


num1=$1
num2=$2
num3=$3

# Find the biggest number


if [ "$num1" -ge "$num2" ] && [ "$num1" -ge "$num3" ]; then
echo "Biggest number is: $num1"
elif [ "$num2" -ge "$num1" ] && [ "$num2" -ge "$num3" ]; then
echo "Biggest number is: $num2"
else
echo "Biggest number is: $num3"
fi

OUTPUT:

Case 1: Correct argument

Case 2: Missing arguments

4
PRACTICAL – 04.

Design, develop and implement a shell script that takes a valid directory name as an argument and
recursively descend all the subdirectories find its maximum length of any file in that hierarchy and
writes this maximum value to the second output.

# Check if exactly 2 arguments are passed


if [ $# -ne 2 ]; then
echo "Usage: $0 <directory> <output_file>"
exit 1
fi

dir=$1
output_file=$2

# Check if the given directory is valid


if [ ! -d "$dir" ]; then
echo "Error: $dir is not a valid directory."
exit 1
fi

# Initialize maximum length


max_length=0

# Loop through all files recursively


while IFS= read -r -d '' file
do
filename=$(basename "$file")
length=${#filename}
if [ "$length" -gt "$max_length" ]; then
max_length=$length
fi
done < <(find "$dir" -type f -print0)

# Write the result to the output file


echo "$max_length" > "$output_file"
echo "Maximum filename length is $max_length. Saved to $output_file."

OUTPUT:

output.txt

5
PRACTICAL – 05.
Design and implement a shell script that computes the gross salary of a employee according
to the following rules:
i ) If basic salary is <1500 then HRA=10% of the basic and DA=90% of the basic
ii) If the basic salary is>=1500 then HRA=500/- and DA=98% of the basic
The basic salary is entered interactively through the key board.

# Prompt user to enter basic salary


echo "Enter Basic Salary:"
read basic

# Check if input is a valid number


if ! [[ "$basic" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
echo "Error: Please enter a valid numeric salary."
exit 1
fi

# Calculate HRA and DA based on rules


if (( $(echo "$basic < 1500" | bc -l) )); then
hra=$(echo "scale=2; $basic * 0.10" | bc)
da=$(echo "scale=2; $basic * 0.90" | bc)
else
hra=500
da=$(echo "scale=2; $basic * 0.98" | bc)
fi

# Calculate gross salary


gross=$(echo "scale=2; $basic + $hra + $da" | bc)

# Output the result


echo " "
echo "Basic Salary : $basic"
echo "HRA : $hra"
echo "DA : $da"
echo "Gross Salary : $gross"
echo " "

OUTPUT:
If basic < 1500 → HRA = 10%, DA = 90%

6
If basic >= 1500 → HRA = 500, DA = 98%.

7
PRACTICAL – 06.
Design, Develop and implement an interactive file handling shell program. Let it offer the
user the choice of copying removing, renaming, or linking files. Once the user has made a
choice have the same program mask the user for the necessary information, such as the file
name ,new name and so on.

#!/bin/bash
while true
do
echo " "
echo " Interactive File Handling Program"
echo " "
echo "1. Copy a file"
echo "2. Remove a file"
echo "3. Rename a file"
echo "4. Create a link to a file"
echo "5. Exit"
echo " "
echo -n "Enter your choice [1-5]: "
read choice

case $choice in
1)
echo -n "Enter source file name: "
read src
if [ ! -f "$src" ]; then
echo "File does not exist!"
else
echo -n "Enter destination file name: "
read dest
cp "$src" "$dest"
echo "File copied to $dest."
fi
;;
2)
echo -n "Enter file name to remove: "
read file
if [ ! -f "$file" ]; then
echo "File does not exist!"
else
rm "$file"
echo "File $file removed."
fi
;;
3)
echo -n "Enter current file name: "
read oldname
if [ ! -f "$oldname" ]; then
echo "File does not exist!"
else
echo -n "Enter new file name: "
read newname
mv "$oldname" "$newname"

8
echo "File renamed to $newname."
fi
;;
4)
echo -n "Enter existing file name: "
read original
if [ ! -f "$original" ]; then
echo "File does not exist!"
else
echo -n "Enter link name: "
read linkname
ln "$original" "$linkname"
echo "Link $linkname created for $original."
fi
;;
5)
e
*) esac c
h
o
"
E
x
i
t
i
n
g
p
r
o
g
r
a
m
.
G
o
o
d
b
y
e
!
"
b
r
e
a
k
;;

echo "Invalid choice! Please select 1-5."


;;

9
echo ""
done

OUTPUT:

10
PRACTICAL – 07.
Design, Develop and implement a shell script to perform the following string operations:
I) To extract a sub-string from a given string.
II) To find the length of a given string.

#!/bin/bash

echo " "


echo " String Operations Menu"
echo " "
echo "1. Extract a Substring"
echo "2. Find Length of a String"
echo "3. Exit"
echo " "

while true
do
echo -n "Enter your choice [1-3]: "
read choice

case $choice in
1)
e
c
h
o
-
n
"
E
n
2) t
e
r
t
h
e
3) s
t
*) esac r
i
n
g
:
"
r
e
a
d
s
t
r
echo -n
"Enter

11
starting E
positio n
n (0- t
based e
index): r
" read t
start h
e e
c s
h t
o r
- i
n n
" g
E :
n "
t r
e e
r a
l d
e s
n t
g r
t length=${#str}
h echo "Length of the string: $length"
o ;;
f
s e
u c
b h
s o
t "
r E
i x
n i
g t
: i
" n
r g
e p
a r
d o
l g
e r
n a
sub=${str:$start:$len} m
echo "Extracted Substring: \"$sub\"" .
;; G
o
e o
c d
h b
o y
- e
n !
" "

12
b ;;
r
e echo "Invalid choice! Please select 1, 2, or 3."
a ;;
k

echo ""
done

13
OUTPUT:

14
PRACTICAL – 08.
Design, Develop and implement a shell script that display all the links toa file specified as
the first argument to the script. The second argument, which iws optional, can be used to
specify in which the search is to begin in current working directory, In either case, the
starting directory as well as all its subdirectories at all levels must be searched. The script
need not include any error checking.

#!/bin/bash

# Get the target filename from the first argument


target_file=$1

# If a second argument (search directory) is provided, use it; otherwise use current directory
search_dir=${2:-"."}

# Get the inode number of the target file


target_inode=$(ls -i "$target_file" | awk '{print $1}')

# Search and display all files with the same inode


find "$search_dir" -inum "$target_inode"

OUTPUT:
Case 1: Search from the current directory

Case 2: Search starting from a specific directory

15
PRACTICAL – 09.
Design, Develop and implement a shell script that reports the logging in of a specified user
within one minute after he/she logs in. The script automatically terminates if the specified
user does not login during a specified period of time.

# Get the username to monitor (first argument)


user_to_monitor=$1

# Set the time limit in seconds (for example, 5 minutes = 300 seconds)
time_limit=300

# Track the start time


start_time=$(date +%s)

# Start monitoring the user login


while true; do
# Get the current time
current_time=$(date +%s)

# Check if the user has logged in (using `who` to get current users)
if who | grep -q "$user_to_monitor"; then
echo "$user_to_monitor has logged in!"
break
fi

# Check if the time limit has been exceeded


if (( current_time - start_time >= time_limit )); then
echo "The user $user_to_monitor did not log in within $time_limit seconds."
break
fi

# Wait for 10 seconds before checking again


sleep 10
done

OUTPUT:
Run the script to monitor a user (example_user) for a login:

If the user logs in within 5 minutes:

If the user does not log in within the time limit (5 minutes):

16
PRACTICAL – 10.
Design, Develop and implement a shell script that folds long lines into 40 columns. Thus any
line that exceeds 40 characters must be broken after 40th ; a\ is to be appended as the
indication of folding and the. processing is to be continued with the residue. The input is to
be through a text file created by the user.

#!/bin/bash

# Get the input file name from the first argument


input_file=$1

# Read the file line by line


while IFS= read -r line
do
while [ ${#line} -gt 40 ]
do
# Print the first 40 characters with '\' at the end
echo "${line:0:40}\\"
# Keep the rest for the next loop
line=${line:40}
done
# Print the remainder of the line (if any)
echo "$line"
done < "$input_file"

OUTPUT:
Run the script:

terminal output :

17
PRACTICAL – 11.
Design, Develop and implement a shell script to implement terminal locking (similar to the
lock command) .it should prompt the user for the password .after accepting the password
entered by the user it must prompt again for the matching password as confirmation and if
match occurs it must lock the keyword until a matching password is entered again by the user
,note that the script must be written to disregard BREAK, control-D. No time limit need be
implemented for the lock duration.

trap '' 2 3 15
# Ask for the password and confirmation
echo -n "Set your lock password: "
stty -echo
read password
echo
echo -n "Confirm your password: "
read confirm
stty echo
echo
# Check if passwords match
if [ "$password" != "$confirm" ]; then
echo "Password mismatch! Exiting."
exit 1
fi
# Terminal is now locked
echo "Terminal is locked. Enter the correct password to unlock."

while true
do
echo -n "Unlock password: "
stty -echo
read try
stty echo
echo
if [ "$try" == "$password" ]; then
echo "Terminal Unlocked."
break
else
echo "Incorrect password. Terminal still locked."
fi
done

OUTPUT:

18
PRACTICAL – 12.
Design , Develop and Implement a shell script that delete all lines containing a specific word
in one or more file supplied as argument to it

#!/bin/bash

# Check if at least two arguments are given (word + at least 1 file)


if [ "$#" -lt 2 ]; then
echo "Usage: $0 <word> <file1> [file2 file3 ...]"
exit 1
fi

# First argument is the word to search for


word=$1

# Shift the arguments so $@ now contains only filenames


shift

# Loop through each file


for file in "$@"
do
if [ -f "$file" ]; then
# Use sed to delete lines containing the word (in-place)
sed -i "/$word/d" "$file"
echo "Deleted lines containing \"$word\" from: $file"
else
echo "File not found: $file"
fi
done

OUTPUT:
file1.txt

file2.txt

19
Running the Script:

Terminal Output:

20

You might also like