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

Shell Script

The scripts contain functions for system monitoring, number calculations, text manipulation, file operations and log file parsing. Functions are defined to check server usage via email, calculate largest/smallest/sum of numbers, generate Fibonacci series, reverse text, count files in a directory, extract CSV columns, search/move files by extension and extract high requesting IPs from logs.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Shell Script

The scripts contain functions for system monitoring, number calculations, text manipulation, file operations and log file parsing. Functions are defined to check server usage via email, calculate largest/smallest/sum of numbers, generate Fibonacci series, reverse text, count files in a directory, extract CSV columns, search/move files by extension and extract high requesting IPs from logs.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Write a script to check server usage and if it is 20% full, the script should
send you an email.

#!/bin/bash

# Set the threshold for server usage (in percentage)


threshold=20

# Get the current server usage percentage


server_usage=$(df -h / | awk 'NR==2 {print $(NF-1)}' | cut -d'%' -f1)

# Check if server usage is equal to or exceeds the threshold


if [ "$server_usage" -ge "$threshold" ]; then
# Email subject and body
subject="Server Usage Alert"
body="Server usage is at $server_usage%. Please check and take necessary
actions."

# Email recipient (replace with your email address)


recipient="[email protected]"

# Send email using the 'mail' command


echo "$body" | mail -s "$subject" "$recipient"

echo "Email sent successfully."


else
echo "Server usage is below the threshold. No email sent."
fi

2. Write a shell script for below number based topics.


- Find biggest of two numbers
- Find biggest of three numbers
- Find biggest of n numbers
- Find sum of n numbers
- Find the smallest of n numbers
- Find the biggest of n numbers
- Find whether the number is odd or even

#!/bin/bash

# Function to find the biggest of two numbers


find_biggest_of_two() {
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2

if [ "$num1" -gt "$num2" ]; then


echo "The biggest number is: $num1"
else
echo "The biggest number is: $num2"
fi
}

# Function to find the biggest of three numbers


find_biggest_of_three() {
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
echo "Enter the third number:"
read num3

if [ "$num1" -gt "$num2" ] && [ "$num1" -gt "$num3" ]; then


echo "The biggest number is: $num1"
elif [ "$num2" -gt "$num1" ] && [ "$num2" -gt "$num3" ]; then
echo "The biggest number is: $num2"
else
echo "The biggest number is: $num3"
fi
}

# Function to find the biggest of n numbers


find_biggest_of_n() {
echo "Enter the count of numbers:"
read count

if [ "$count" -le 0 ]; then


echo "Invalid count. Please enter a positive integer."
return
fi

echo "Enter the numbers separated by spaces:"


read -a numbers

biggest=${numbers[0]}

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


if [ "${numbers[i]}" -gt "$biggest" ]; then
biggest="${numbers[i]}"
fi
done

echo "The biggest number is: $biggest"


}

# Function to find the sum of n numbers


find_sum_of_n() {
echo "Enter the count of numbers:"
read count

if [ "$count" -le 0 ]; then


echo "Invalid count. Please enter a positive integer."
return
fi

echo "Enter the numbers separated by spaces:"


read -a numbers

sum=0

for ((i = 0; i < count; i++)); do


sum=$((sum + numbers[i]))
done

echo "The sum of the numbers is: $sum"


}
# Function to find the smallest of n numbers
find_smallest_of_n() {
echo "Enter the count of numbers:"
read count

if [ "$count" -le 0 ]; then


echo "Invalid count. Please enter a positive integer."
return
fi

echo "Enter the numbers separated by spaces:"


read -a numbers

smallest=${numbers[0]}

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


if [ "${numbers[i]}" -lt "$smallest" ]; then
smallest="${numbers[i]}"
fi
done

echo "The smallest number is: $smallest"


}

# Function to find the biggest of n numbers


find_biggest_of_n() {
echo "Enter the count of numbers:"
read count

if [ "$count" -le 0 ]; then


echo "Invalid count. Please enter a positive integer."
return
fi

echo "Enter the numbers separated by spaces:"


read -a numbers

biggest=${numbers[0]}

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


if [ "${numbers[i]}" -gt "$biggest" ]; then
biggest="${numbers[i]}"
fi
done

echo "The biggest number is: $biggest"


}

# Function to check whether a number is odd or even


check_odd_even() {
echo "Enter a number:"
read num

if [ "$((num % 2))" -eq 0 ]; then


echo "The number is even."
else
echo "The number is odd."
fi
}
# Main menu
while true; do
echo -e "\nNumber-based Script Menu:"
echo "1. Find the biggest of two numbers"
echo "2. Find the biggest of three numbers"
echo "3. Find the biggest of n numbers"
echo "4. Find the sum of n numbers"
echo "5. Find the smallest of n numbers"
echo "6. Find the biggest of n numbers"
echo "7. Check whether a number is odd or even"
echo "8. Exit"

read -p "Enter your choice (1-8): " choice

case $choice in
1) find_biggest_of_two ;;
2) find_biggest_of_three ;;
3) find_biggest_of_n ;;
4) find_sum_of_n ;;
5) find_smallest_of_n ;;
6) find_biggest_of_n ;;
7) check_odd_even ;;
8) echo "Exiting. Goodbye!"; exit ;;
*) echo "Invalid choice. Please enter a number between 1 and 8." ;;
esac
done

3. Wrtie a script to generate Fibonacci series where length of series is based on


the user input.

#!/bin/bash

# Function to generate Fibonacci series


generate_fibonacci() {
echo "Enter the length of the Fibonacci series:"
read length

# Handle invalid input


if [ "$length" -lt 1 ]; then
echo "Invalid length. Please enter a positive integer."
return
fi

# First two numbers in the Fibonacci series


a=0
b=1

echo -n "Fibonacci series of length $length: "

for ((i = 0; i < length; i++)); do


echo -n "$a "

# Calculate the next Fibonacci number


next=$((a + b))

# Update values for the next iteration


a=$b
b=$next
done

echo
}

# Call the function to generate Fibonacci series


generate_fibonacci

4. Write a script to reverse print a file content without using tac.

Check Manoj or Putti Notes.

5. Write a script to reverse print a word without using rev.

#!/bin/bash

echo "Enter a word:"


read word

length=${#word}
reversed=""

# Iterate through the characters of the word in reverse order


for (( i = length - 1; i >= 0; i-- )); do
reversed="${reversed}${word:$i:1}"
done

echo "Reversed word: $reversed"

6. Write a Bash script that takes a directory path as an argument and counts the
number of files and directories in that directory.

#!/bin/bash

if [ "$#" -ne 1 ]; then


echo "Usage: $0 <directory_path>"
exit 1
fi

directory_path="$1"

if [ ! -d "$directory_path" ]; then
echo "Error: Not a valid directory path."
exit 1
fi

# Count the number of files and directories


num_files=$(find "$directory_path" -maxdepth 1 -type f | wc -l)
num_directories=$(find "$directory_path" -maxdepth 1 -type d | wc -l)

echo "Number of files in '$directory_path': $num_files"


echo "Number of directories in '$directory_path': $num_directories"

7. Create a Bash script that reads a CSV file and prints the number of lines in it.

#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <csv_file>"
exit 1
fi

csv_file="$1"

if [ ! -f "$csv_file" ]; then
echo "Error: Not a valid CSV file."
exit 1
fi

# Count the number of lines in the CSV file


num_lines=$(wc -l < "$csv_file")

echo "Number of lines in '$csv_file': $num_lines"

8. Create a Bash script that reads a CSV file and prints 2nd,5th column in it.

#!/bin/bash

if [ "$#" -ne 1 ]; then


echo "Usage: $0 <csv_file>"
exit 1
fi

csv_file="$1"

if [ ! -f "$csv_file" ]; then
echo "Error: Not a valid CSV file."
exit 1
fi

# Print the 2nd and 5th columns from the CSV file
awk -F',' '{print $2, $5}' "$csv_file"

9. Write a Bash script that searches for all files with a specific extension (e.g.,
.txt) in a given directory and its subdirectories.
- moves them to a separate folder.

#!/bin/bash

if [ "$#" -ne 2 ]; then


echo "Usage: $0 <source_directory> <destination_directory>"
exit 1
fi

source_directory="$1"
destination_directory="$2"

if [ ! -d "$source_directory" ]; then
echo "Error: Not a valid source directory."
exit 1
fi

if [ ! -d "$destination_directory" ]; then
echo "Error: Not a valid destination directory."
exit 1
fi

# Set the file extension to search for


file_extension=".txt"

# Search for files with the specified extension in the source directory and its
subdirectories
find "$source_directory" -type f -name "*$file_extension" -exec mv -t
"$destination_directory" {} +

echo "Files with '$file_extension' extension moved from '$source_directory' to


'$destination_directory'."

10. Write a Bash script that searches for all files with a specific extension
(e.g., .txt)
- Copy then to a separate folder call backup with the file and directory name
appended with backup

#!/bin/bash

if [ "$#" -ne 1 ]; then


echo "Usage: $0 <source_directory>"
exit 1
fi

source_directory="$1"
backup_directory="backup"

if [ ! -d "$source_directory" ]; then
echo "Error: Not a valid source directory."
exit 1
fi

# Create the backup directory if it doesn't exist


mkdir -p "$backup_directory"

# Set the file extension to search for


file_extension=".txt"

# Search for files with the specified extension in the source directory and its
subdirectories
find "$source_directory" -type f -name "*$file_extension" -exec bash -c '
for file do
backup_name="${file##*/}_backup"
cp "$file" "$backup_directory/$backup_name"
done
' bash {} +

echo "Files with '$file_extension' extension copied to '$backup_directory' with


'backup' suffix."

11. Create a Bash script that reads a log file and extracts all IP addresses that
made more than 100 requests in a given time frame.

#!/bin/bash

if [ "$#" -ne 1 ]; then


echo "Usage: $0 <log_file>"
exit 1
fi

log_file="$1"

if [ ! -f "$log_file" ]; then
echo "Error: Not a valid log file."
exit 1
fi

# Set the time frame in seconds (adjust as needed)


time_frame=3600 # 1 hour

# Extract IP addresses that made more than 100 requests in the given time frame
awk -v time_frame="$time_frame" '$4 >= (systime() - time_frame) { print $1 }'
"$log_file" \
| sort \
| uniq -c \
| awk '$1 > 100 { print $2 }'

12. Write a Bash script that checks the disk usage of a specific directory and
sends an email notification if the usage exceeds a certain threshold.

#!/bin/bash

# Set the directory to check


directory_to_check="/path/to/your/directory"

# Set the disk usage threshold in percentage


threshold=90

# Get the current disk usage percentage for the specified directory
disk_usage=$(df -h "$directory_to_check" | awk 'NR==2 {print $(NF-1)}' | cut -d'%'
-f1)

# Check if the disk usage exceeds the threshold


if [ "$disk_usage" -gt "$threshold" ]; then
# Email subject and body
subject="Disk Usage Alert"
body="Disk usage for '$directory_to_check' is at $disk_usage%. Please check and
take necessary actions."

# Email recipient (replace with your email address)


recipient="[email protected]"

# Send email using the 'mail' command


echo "$body" | mail -s "$subject" "$recipient"

echo "Email sent successfully."


else
echo "Disk usage for '$directory_to_check' is below the threshold. No email
sent."
fi

13. Create a Bash script that reads a configuration file and installs the required
packages listed in it using a package manager
Script should able to identify the current linux type and use the appropriate
pkg manager - e.g., apt or yum.
#!/bin/bash

# Function to determine the package manager


get_package_manager() {
if command -v apt-get &> /dev/null; then
echo "apt"
elif command -v yum &> /dev/null; then
echo "yum"
else
echo "Unsupported package manager. Exiting."
exit 1
fi
}

# Function to install packages using apt


install_packages_apt() {
sudo apt-get update
sudo apt-get install -y "$@"
}

# Function to install packages using yum


install_packages_yum() {
sudo yum install -y "$@"
}

# Check if a configuration file is provided as an argument


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

config_file="$1"

if [ ! -f "$config_file" ]; then
echo "Error: Not a valid configuration file."
exit 1
fi

# Determine the package manager


package_manager=$(get_package_manager)

# Read the configuration file and install packages


while IFS= read -r package; do
if [ -n "$package" ]; then
echo "Installing $package using $package_manager..."
case "$package_manager" in
"apt") install_packages_apt "$package" ;;
"yum") install_packages_yum "$package" ;;
esac
fi
done < "$config_file"

echo "Package installation complete."

14. Create a Bash script that monitors the CPU and memory usage of a server and
sends an alert if the usage exceeds a certain threshold.
The script should also log the usage details with timestamp.
#!/bin/bash

# Set the threshold values for CPU and memory usage


cpu_threshold=90
memory_threshold=90

# Set the log file path


log_file="/var/log/usage_monitor.log"

# Function to get the current timestamp


get_timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}

# Function to log usage details


log_usage() {
echo "$(get_timestamp) - CPU: $cpu_usage%, Memory: $memory_usage%" >>
"$log_file"
}

# Function to send alert


send_alert() {
# Email subject and body
subject="Server Usage Alert"
body="CPU or memory usage has exceeded the threshold. Check the log for
details."

# Email recipient (replace with your email address)


recipient="[email protected]"

# Send email using the 'mail' command


echo "$body" | mail -s "$subject" "$recipient"

echo "Email sent successfully."


}

# Get CPU and memory usage


cpu_usage=$(top -b -n 1 | awk '/^%Cpu/ {print int($2)}')
memory_usage=$(free -m | awk '/^Mem:/ {print int(($3/$2)*100)}')

# Log the usage details


log_usage

# Check if CPU or memory usage exceeds the threshold


if [ "$cpu_usage" -gt "$cpu_threshold" ] || [ "$memory_usage" -gt
"$memory_threshold" ]; then
send_alert
fi

In Future

1. Create a Bash script that takes a URL as input and checks if the website is up
or down using the curl command.
The script should print "Website is up" if the HTTP response is 200, and
"Website is down" otherwise.

#!/bin/bash
# Function to check if the website is up or down
check_website_status() {
url="$1"
http_status=$(curl -s -o /dev/null -w "%{http_code}" "$url")

if [ "$http_status" -eq 200 ]; then


echo "Website is up"
else
echo "Website is down"
fi
}

# Check if a URL is provided as an argument


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

website_url="$1"

# Call the function to check the website status


check_website_status "$website_url"

2. Write a Bash script that compresses all files in a directory (excluding


subdirectories) into a single tar.gz file.

#!/bin/bash

# Check if a directory path is provided as an argument


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

directory_path="$1"

# Check if the specified path is a directory


if [ ! -d "$directory_path" ]; then
echo "Error: Not a valid directory path."
exit 1
fi

# Get the current date and time for the tar.gz file name
timestamp=$(date +"%Y%m%d_%H%M%S")

# Create a tar.gz file containing all files in the directory


tar -czf "compressed_files_$timestamp.tar.gz" -C "$directory_path" -- *

echo "Compression complete. The tar.gz file is named:


compressed_files_$timestamp.tar.gz"

3. Write a Bash script that automates the backup process of a database.


The script should dump the database, compress the backup file, and upload it to
a remote storage location.

#!/bin/bash

# Load configuration from a separate file


source /path/to/backup_config.sh
# Check if required tools are installed
command -v mysqldump >/dev/null 2>&1 || { echo >&2 "mysqldump is required but not
installed. Aborting."; exit 1; }
command -v tar >/dev/null 2>&1 || { echo >&2 "tar is required but not installed.
Aborting."; exit 1; }
command -v curl >/dev/null 2>&1 || { echo >&2 "curl is required but not installed.
Aborting."; exit 1; }

# Get the current date and time for the backup file name
timestamp=$(date +"%Y%m%d_%H%M%S")

# Dump the database


mysqldump -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" >
"backup_$timestamp.sql"

# Compress the backup file


tar -czf "backup_$timestamp.tar.gz" "backup_$timestamp.sql"

# Upload the backup file to a remote storage location


curl -T "backup_$timestamp.tar.gz" -u "$REMOTE_STORAGE_USER:
$REMOTE_STORAGE_PASSWORD" "$REMOTE_STORAGE_URL"

# Remove temporary files


rm "backup_$timestamp.sql" "backup_$timestamp.tar.gz"

echo "Backup process complete."

Now, create a separate configuration file (backup_config.sh) with sensitive


information:

# backup_config.sh

# Database configuration
DB_HOST="your_database_host"
DB_USER="your_database_user"
DB_PASSWORD="your_database_password"
DB_NAME="your_database_name"

# Remote storage configuration


REMOTE_STORAGE_USER="your_remote_storage_user"
REMOTE_STORAGE_PASSWORD="your_remote_storage_password"
REMOTE_STORAGE_URL="your_remote_storage_url"

Save both scripts, make them executable, and then you can run the backup script:

chmod +x backup_script.sh
./backup_script.sh

This script will dump the database, compress the backup file, and upload it to a
remote storage location using cURL.
Adjust the script according to your specific database and storage configurations.

4. Write a Bash script that automates the deployment of a web application to a


remote server.
The script should pull the latest code from a version control system, build the
application, and deploy it to the server.

#!/bin/bash
# Load configuration from a separate file
source /path/to/deployment_config.sh

# Check if required tools are installed


command -v git >/dev/null 2>&1 || { echo >&2 "git is required but not installed.
Aborting."; exit 1; }
command -v mvn >/dev/null 2>&1 || { echo >&2 "maven is required but not installed.
Aborting."; exit 1; }
command -v ssh >/dev/null 2>&1 || { echo >&2 "ssh is required but not installed.
Aborting."; exit 1; }

# Get the current date and time for log purposes


timestamp=$(date +"%Y%m%d_%H%M%S")

# Pull the latest code from the version control system (assuming git)
git clone "$REPOSITORY_URL" "$LOCAL_REPO_PATH" || { echo >&2 "Failed to clone the
repository. Aborting."; exit 1; }

# Build the application (assuming Maven)


cd "$LOCAL_REPO_PATH" || { echo >&2 "Failed to change directory to
$LOCAL_REPO_PATH. Aborting."; exit 1; }
mvn clean install || { echo >&2 "Maven build failed. Aborting."; exit 1; }

# Deploy the application to the remote server


scp -r "$LOCAL_REPO_PATH/target/your_application.jar"
"$REMOTE_SERVER_USER@$REMOTE_SERVER_IP:$REMOTE_SERVER_DEPLOY_PATH" || { echo >&2
"Failed to deploy the application. Aborting."; exit 1; }

# Restart the application on the remote server (adjust as needed)


ssh "$REMOTE_SERVER_USER@$REMOTE_SERVER_IP" "systemctl restart
your_application.service" || { echo >&2 "Failed to restart the application.
Aborting."; exit 1; }

# Cleanup: Remove the local repository


rm -rf "$LOCAL_REPO_PATH"

echo "Deployment process complete."

Now, create a separate configuration file (deployment_config.sh) with your specific


details:

# deployment_config.sh

# Version control system configuration (Git)


REPOSITORY_URL="your_repository_url"
LOCAL_REPO_PATH="/path/to/local/repo"

# Remote server configuration


REMOTE_SERVER_USER="your_remote_server_user"
REMOTE_SERVER_IP="your_remote_server_ip"
REMOTE_SERVER_DEPLOY_PATH="/path/to/remote/deployment/directory"

Replace placeholder values with your actual version control system and server
details.

Save both scripts, make them executable, and then you can run the deployment
script:
chmod +x deploy_script.sh
./deploy_script.sh

This script pulls the latest code from a Git repository, builds the application
using Maven, and deploys it to a remote server using SCP.
Adjust the script according to your specific application, version control system,
and deployment configurations.

5. Create a Bash script that automates the deployment of containerized applications


using Docker.
The script should pull the latest container images, run the containers with the
appropriate configurations, and manage the container lifecycle.

#!/bin/bash

# Load configuration from a separate file


source /path/to/docker_config.sh

# Check if Docker is installed


command -v docker >/dev/null 2>&1 || { echo >&2 "Docker is required but not
installed. Aborting."; exit 1; }

# Get the current date and time for log purposes


timestamp=$(date +"%Y%m%d_%H%M%S")

# Pull the latest container images


docker pull "$IMAGE_NAME:$IMAGE_TAG" || { echo >&2 "Failed to pull the latest
container image. Aborting."; exit 1; }

# Stop and remove existing containers (if any)


docker stop "$CONTAINER_NAME" >/dev/null 2>&1
docker rm "$CONTAINER_NAME" >/dev/null 2>&1

# Run the container with appropriate configurations


docker run -d \
--name "$CONTAINER_NAME" \
-p "$HOST_PORT:$CONTAINER_PORT" \
-e ENV_VARIABLE1=value1 \
-e ENV_VARIABLE2=value2 \
"$IMAGE_NAME:$IMAGE_TAG" || { echo >&2 "Failed to run the container.
Aborting."; exit 1; }

echo "Deployment process complete."

Now, create a separate configuration file (docker_config.sh) with your specific


details:

# docker_config.sh

# Container image configuration


IMAGE_NAME="your_container_image_name"
IMAGE_TAG="your_container_image_tag"

# Container configuration
CONTAINER_NAME="your_container_name"
HOST_PORT="your_host_port"
CONTAINER_PORT="your_container_port"

Replace placeholder values with your actual container image and deployment details.
Save both scripts, make them executable, and then you can run the deployment
script:

chmod +x deploy_docker_script.sh
./deploy_docker_script.sh

This script pulls the latest container image, stops and removes existing containers
(if any), and runs the container with the specified configurations.
Adjust the script according to your specific Docker container configurations and
deployment requirements.

You might also like