0% found this document useful (0 votes)
8 views7 pages

Linux Practicles

The document contains a series of shell scripts that perform various tasks, including calculating factorials, listing directory files, counting word occurrences, checking file permissions, deleting lines from files, calculating employee gross salary, and monitoring user logins. Each script includes input validation and error handling to ensure proper execution. The scripts demonstrate practical applications of shell scripting for file and user management in a Unix-like environment.

Uploaded by

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

Linux Practicles

The document contains a series of shell scripts that perform various tasks, including calculating factorials, listing directory files, counting word occurrences, checking file permissions, deleting lines from files, calculating employee gross salary, and monitoring user logins. Each script includes input validation and error handling to ensure proper execution. The scripts demonstrate practical applications of shell scripting for file and user management in a Unix-like environment.

Uploaded by

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

1. Write a shell script to find factorial of a given integer.

#!/bin/bash

# Function to calculate factorial


factorial() {
local num=$1
local result=1

for ((i=1; i<=num; i++)); do


result=$((result * i))
done

echo $result
}

# Input prompt
read -p "Enter a number to find its factorial: " number

# Check if the input is a non-negative integer


if [[ ! "$number" =~ ^[0-9]+$ ]] || [ "$number" -lt 0 ]; then
echo "Please enter a valid non-negative integer."
else
result=$(factorial $number)
echo "The factorial of $number is: $result"
fi

2. Write a shell script to list all of the directory files in a directory.

#!/bin/bash

# Input prompt
read -p "Enter the directory path to list files: " directory

# Check if the directory exists


if [ -d "$directory" ]; then
echo "Listing files in the directory '$directory':"
# List files in the directory (not directories)
find "$directory" -maxdepth 1 -type f
else
echo "The provided path is not a valid directory."
fi

3. Write a shell script that accepts a list of file names as its arguments, counts
and reports the occurrence of each word that is present in the first argument file
on other argument files.

#!/bin/bash

# Check if there are at least 2 arguments


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

# The first argument is the file whose words we will count


first_file="$1"
# Check if the first file exists
if [ ! -f "$first_file" ]; then
echo "Error: File '$first_file' not found!"
exit 1
fi

# Loop through each word in the first file


echo "Word occurrences from '$first_file' in other files:"
for word in $(cat "$first_file" | tr -s ' ' '\n' | sort | uniq); do
echo "Word: '$word'"
for file in "${@:2}"; do
# Check if the file exists
if [ ! -f "$file" ]; then
echo "Error: File '$file' not found!"
continue
fi

# Count the occurrences of the word in the current file


count=$(grep -wo "$word" "$file" | wc -l)
echo " - $file: $count occurrences"
done
echo ""
done

4. Write a shell script that displays a list of all the files in the current
directory to which the user has read, write and execute permissions.

#!/bin/bash

# Get the current directory


current_dir=$(pwd)

# List all files in the current directory with read, write, and execute permissions
for the user
echo "Files in the current directory ($current_dir) with read, write, and execute
permissions for the user:"

# Loop through all files in the current directory


for file in "$current_dir"/*; do
# Check if the user has read, write, and execute permissions
if [ -f "$file" ] && [ -r "$file" ] && [ -w "$file" ] && [ -x "$file" ]; then
echo "$file"
fi
done

5. Write a shell script that deletes all lines containing a specified word in one
or more files supplied as arguments to it.

#!/bin/bash

# Check if at least 2 arguments are provided (word and file(s))


if [ $# -lt 2 ]; then
echo "Usage: $0 <word> <file1> [file2 ...]"
exit 1
fi
# The first argument is the word to search for
word="$1"
shift # Shift to move the file arguments

# Loop through each file passed as argument


for file in "$@"; do
# Check if the file exists
if [ ! -f "$file" ]; then
echo "Error: File '$file' not found!"
continue
fi

# Create a temporary file to store the modified content


temp_file=$(mktemp)

# Remove lines containing the specified word and save to the temp file
grep -v "$word" "$file" > "$temp_file"

# Move the modified content back to the original file


mv "$temp_file" "$file"

echo "Lines containing '$word' have been deleted from '$file'."


done

6. Shell script to display the period for which a given user has been working in
the system.

#!/bin/bash

# Check if a username is provided


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

# Get the username from the argument


username="$1"

# Get the login time of the user


login_time=$(who -u | grep "^$username" | awk '{print $3, $4}')

# Check if the user is logged in


if [ -z "$login_time" ]; then
echo "User '$username' is not currently logged in."
exit 1
fi

# Convert the login time to the format "YYYY-MM-DD HH:MM"


login_time_epoch=$(date -d "$login_time" +%s)

# Get the current time in seconds since epoch


current_time_epoch=$(date +%s)

# Calculate the difference in seconds


time_diff=$((current_time_epoch - login_time_epoch))

# Convert the difference to hours, minutes, and seconds


hours=$((time_diff / 3600))
minutes=$(((time_diff % 3600) / 60))
seconds=$((time_diff % 60))

# Display the working period


echo "User '$username' has been working for: $hours hours, $minutes minutes, and
$seconds seconds."

7. Aim to compute gross salary of an employee, accordingly to rule given below.

If basic salary is <15000 then HRA =10% of basic and DA =90% of basic

If basic salary is >=15000 then HRA =500 and DA =98% of basic.

#!/bin/bash

# Prompt the user for the basic salary


read -p "Enter the basic salary of the employee: " basic_salary

# Check if the entered basic salary is a valid number


if [[ ! "$basic_salary" =~ ^[0-9]+$ ]] || [ "$basic_salary" -lt 0 ]; then
echo "Please enter a valid positive number for the basic salary."
exit 1
fi

# Initialize HRA and DA


if [ "$basic_salary" -lt 15000 ]; then
# If basic salary is less than 15000
HRA=$(echo "$basic_salary * 0.10" | bc)
DA=$(echo "$basic_salary * 0.90" | bc)
else
# If basic salary is greater than or equal to 15000
HRA=500
DA=$(echo "$basic_salary * 0.98" | bc)
fi

# Calculate the gross salary


gross_salary=$(echo "$basic_salary + $HRA + $DA" | bc)

# Display the results


echo "Basic Salary: $basic_salary"
echo "HRA: $HRA"
echo "DA: $DA"
echo "Gross Salary: $gross_salary"

8. Write an awk script to find out total number of books sold in each discipline as
well astotal book sold using associate array down table as given

Electrical 34 electrical 80

Mechanical 67 computers 43

Mechanical 65 civil 198

#!/bin/bash

# Data input (assuming it is passed as input or saved in a file)


echo "Electrical 34 electrical 80
Mechanical 67 computers 43
Mechanical 65 civil 198" | awk '
BEGIN {
# Initialize total_books variable to 0
total_books = 0;
}

{
# Sum the books sold in each discipline
discipline[$1] += $2;
discipline[$3] += $4;

# Sum the total number of books sold


total_books += $2 + $4;
}

END {
# Output the results for each discipline
print "Total number of books sold in each discipline:";
for (d in discipline) {
print d ": " discipline[d];
}

# Output the total number of books sold


print "Total books sold: " total_books;
}
'

9. Create a script file called file properties that reads a file name entered and
output its properties

#!/bin/bash

# Prompt the user to enter a file name


read -p "Enter the file name: " filename

# Check if the file exists


if [ ! -e "$filename" ]; then
echo "File '$filename' does not exist."
exit 1
fi

# Output the file properties


echo "File Properties of '$filename':"

# File type (regular file, directory, etc.)


file_type=$(file "$filename")
echo "File type: $file_type"

# File permissions (human-readable)


permissions=$(ls -l "$filename" | awk '{print $1}')
echo "Permissions: $permissions"

# File size in human-readable format


size=$(ls -lh "$filename" | awk '{print $5}')
echo "Size: $size"
# Last modification date
mod_date=$(stat -c %y "$filename")
echo "Last modification date: $mod_date"

# File inode number


inode=$(stat -c %i "$filename")
echo "Inode: $inode"

# File owner and group


owner=$(ls -l "$filename" | awk '{print $3}')
group=$(ls -l "$filename" | awk '{print $4}')
echo "Owner: $owner"
echo "Group: $group"

# Number of links
links=$(ls -l "$filename" | awk '{print $2}')
echo "Number of links: $links"

# Check if the file is a symbolic link


if [ -L "$filename" ]; then
link_target=$(readlink "$filename")
echo "This is a symbolic link, pointing to: $link_target"
fi

10. Write a shell script using expr command to read in a string and display a
suitable message if it doesnot have at least 10 characters.

#!/bin/bash

# Prompt the user to enter a string


echo "Please enter a string:"
read user_input

# Use expr to get the length of the string


length=$(expr length "$user_input")

# Check if the length is less than 10


if [ $length -lt 10 ]; then
echo "The string is too short. It must have at least 10 characters."
else
echo "The string is of sufficient length."
fi

11. Write a shell script that reports the logging in of a specified user within one
minute after he/she logsin. The script automatically terminates if the specified
user does not login during a specified period oftime.

#!/bin/bash

# Check if the correct number of arguments is provided


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

USERNAME=$1
TIMEOUT=$2
CHECK_INTERVAL=1 # Check every second
ELAPSED_TIME=0

# Function to check if the user is logged in


is_user_logged_in() {
who | grep -w "$USERNAME" > /dev/null
}

# Start monitoring
echo "Monitoring login for user: $USERNAME"
echo "Timeout set for: $TIMEOUT seconds"

while [ $ELAPSED_TIME -lt $TIMEOUT ]; do


if is_user_logged_in; then
echo "User '$USERNAME' has logged in."
exit 0
fi
sleep $CHECK_INTERVAL
ELAPSED_TIME=$((ELAPSED_TIME + CHECK_INTERVAL))
done

echo "User '$USERNAME' did not log in within the specified timeout of $TIMEOUT
seconds."
exit 1

You might also like