Shell Script Assignment

·

6 min read

1] Write a shell script to print arguments passed to the script in reverse order

#!/bin/bash

# Check if any arguments are provided
if [ $# -eq 0 ]; then
    echo "No arguments provided."
    exit 1
fi

# Get the total number of arguments
total_args=$#

# Loop through arguments in reverse order
for ((i = total_args; i > 0; i--)); do
    # Print each argument
    echo "Argument $i: ${!i}"
done

${!i} --> it gives the place value


3] Write a script that monitors system performance & sends a mail notification with warning messages about resource usage like RAM, disk usage every 24 hours

#!/bin/bash 

rfree=$(free -m | sed -n '2p' | awk '{print$4}')
duse=$(df -h | awk '{print$5}' | sed -n 5p | sed 's/%//g') 

if [ $rfree -lt 50 ]; then
echo -e "Warning!!!!The ram usage has crossed limit \nThe current free space is $rfree MB" 
| mail -s "High RAM Usage" akashofficial731@gmail.com
else
echo "The current free space available is $rfree MB" | mail -s "RAM Usage" 
akashofficial731@gmail.com
fi

if [ $duse -gt 80 ]; then
echo -e "The disk usage has crossed 80%!!!!!! \n The current disk usage percentage is 
$duse" | mail -s "High Disk Usage" akashofficial731@gmail.com
else
echo "The current disk usage percentage is $duse" | mail -s "Disk Usage" 
akashofficial731@gmail.com
fi

Creating cronjob

crontab –e

00 00 * * * sh 3.sh

And start the postfix service

systemctl start postfix


4] Write a script to that backups of a directory as tar zip file every weekend & store them as versions

#!/bin/bash

source_directory="/home/ec2-user/sc/Assi"
backup_directory="/home/ec2-user/backup"
date=$(date "+%U")
backup_filename="backup_$date.tar.gz"
tar -czf "$backup_directory/$backup_filename" "$source_directory"

5] Write a script to find the files in a directory that were last modified more than 4 weeks ago & delete them, starting with the ones that consume the most space

#!/bin/bash

echo "Enter the path of the dir to search"
read dir

find $dir -type f -mtime +28| xargs du -sh | sort -rh > temp
while read line
do
echo $line | awk '{print$NF}' | xargs rm
done < temp

6] Explain the difference between running a script with './script' and running it with 'nohup ./script &'

  1. Foreground Execution (./script):

    • Blocking Execution: When you run a script with ./script, it runs in the foreground and occupies the terminal. The script's output is visible in the terminal, and you may need to wait for it to finish before you can interact with the shell again.

    • Hangs Up When Terminal Closes: If you close the terminal or disconnect from the session, the script is terminated because it is associated with the terminal. It is tightly bound to the shell session from which it was launched.

  2. Background Execution withnohup ./script &:

    • Background Execution: When you use nohup ./script &, the script is executed in the background. This means it does not tie up the terminal, and you can continue to use the terminal for other tasks while the script runs.

    • Disassociation from Terminal: The nohup (no hang up) command disconnects the script from the terminal, ensuring that the script continues running even if the terminal is closed or the user logs out. The output is redirected to a file named nohup.out by default.

    • Suppressing Hangup Signals:nohup also suppresses the SIGHUP (hangup) signal, so the script is not terminated when the terminal session ends.


7] Read an integer and generate the following pattern :

1

1 2

1 2 3

1 2 3 4

up to 'n' rows

#!/bin/bash

echo "Enter the value of 'n':"
read n

# Outer loop for rows
for ((i = 1; i <= n; i++)); do
    # Inner loop for columns
    for ((j = 1; j <= i; j++)); do
        echo -n "$j " # Print the current number
    done

    # Move to the next line after each row
    echo ""
done


8] Write a script to display the contents of the file in reverse order without using tac command

#!/bin/bash

echo "Enter the filename:"
read filename

if [ -f "$filename" ]; then
    # Use tail to get the last line number
    last_line=$(wc -l < "$filename")

    # Use tail to print the lines in reverse order, rev to reverse characters in each line
    for ((i = last_line; i >= 1; i--)); do
        tail -n "$i" "$filename" | head -n 1 | rev
    done
else
    echo "File not found: $filename"
fi


9] Write a script to reverse a string using while loop

#!/bin/bash

echo "Enter a string:"
read input_string

# Initialize variables
length=${#input_string}
reversed_string=""

# Use a while loop to reverse the string
index=$((length - 1))
while [ $index -ge 0 ]; do
    reversed_string="${reversed_string}${input_string:$index:1}"
    index=$((index - 1))
done

echo "Reversed string: $reversed_string"


10] Read an integer 'n' and generate the following pattern:

1

2 3

4 5 6

7 8 9 10

up to 'n' rows

#!/bin/bash

echo "Enter the value of 'n':"
read n

counter=1

# Outer loop for rows
for ((i = 1; i <= n; i++)); do
    # Inner loop for columns
    for ((j = 1; j <= i; j++)); do
        echo -n "$counter " # Print the current number
        counter=$((counter + 1))
    done

    # Move to the next line after each row
    echo ""
done

echo -n will output the text without moving to the next line, allowing the next command's output to appear on the same line.


11] Write a script that rename a file or directory by replacing its letters with lowercase from uppercase letters

#!/bin/bash

# Function to convert uppercase letters to lowercase
to_lowercase() {
    echo "$1" | tr 'A-Z' 'a-z'
}

# Check if a file or directory name is provided as an argument
if [ $# -eq 0 ]; then
    echo "Usage: $0 <file_or_directory_name>"
    exit 1
fi

# Loop through provided arguments
for item in "$@"; do
    # Check if the item exists
    if [ -e "$item" ]; then
        # Get the lowercase version of the item name
        lowercase_name=$(to_lowercase "$item")

        # Rename the item
        mv -n "$item" "$lowercase_name"

        echo "Renamed '$item' to '$lowercase_name'"
    else
        echo "Error: '$item' not found."
    fi
done


12] Write a script that takes multiple inputs from the user as arguments and only prints the arguments if they are integers

#!/bin/bash

# Function to check if a value is an integer
is_integer() {
    re='^[0-9]+$'
    if [[ $1 =~ $re ]]; then
        return 0
    else
        return 1
    fi
}

# Check if there are arguments provided
if [ "$#" -eq 0 ]; then
    echo "No arguments provided."
    exit 1
fi

echo "Integers provided as arguments:"

# Loop through the provided arguments
for arg in "$@"; do
    if is_integer "$arg"; then
        echo "$arg"
    fi
done