diff --git a/Challenges/Day_1/my_solution_day1.sh b/Challenges/Day_1/my_solution_day1.sh new file mode 100644 index 0000000..961f873 --- /dev/null +++ b/Challenges/Day_1/my_solution_day1.sh @@ -0,0 +1,44 @@ +#!bin/bash/ + +#task1- comments +#this is BashBlazeChallenge- Day1 + +#task2- echo +#echo prints on the screen +echo "This is BashBlazeChallenge- Day1" + +#task3 - variables +name="Shivani" +yeo=2 + +#task4- using variables +echo "My name is $name and YEO is $yeo" + +a=13 b=89 +sum=$(($a+$b)) +echo "The sum of $a and $b is $sum" + +#task5 - using built-in variables +echo "My current working directory is $PWD" +echo "My home directory is $HOME" +echo "The PID of this bash process is $$" + +#task6 - using wildcards +echo "making some files:" +touch day{8..11}.txt +touch hello.sh ls + +echo "Using wildcard- ls .sh" +ls *.sh + +echo "Using wildcard- ls .txt" +ls *.txt + +echo "Using ? wildcard- ls day?.txt" +ls day?.txt + +echo "Using [] wildcard- ls day[1-10].txt" +ls day[1-10].txt + +echo "Using ? wildcard- ls day*" +ls day* diff --git a/Challenges/Day_2/backup_with_rotation.sh b/Challenges/Day_2/backup_with_rotation.sh index 2c5e56f..a3222d6 100644 --- a/Challenges/Day_2/backup_with_rotation.sh +++ b/Challenges/Day_2/backup_with_rotation.sh @@ -1,41 +1,20 @@ -#!/bin/bash +#!bin/bash/ -# Function to display usage information and available options -function display_usage { - echo "Usage: $0 /path/to/source_directory" -} +#we will take source path from user and gets stored in $1 +src_path=$1 -# Check if a valid directory path is provided as a command-line argument -if [ $# -eq 0 ] || [ ! -d "$1" ]; then - echo "Error: Please provide a valid directory path as a command-line argument." - display_usage - exit 1 -fi +#we will store the current date and time in 2 variables +fname="$(date '+%Y-%m-%d')" +time="$(date '+%I-%M-%S')" -# Directory path of the source directory to be backed up -source_dir="$1" +#storing the name of the backup file in f_name +f_name=backup_$fname"_"$time.tar.gz -# Function to create a timestamped backup folder -function create_backup { - local timestamp=$(date '+%Y-%m-%d_%H-%M-%S') # Get the current timestamp - local backup_dir="${source_dir}/backup_${timestamp}" +#this line will zip the files present in $src_path +tar -czf $f_name $src_path - # Create the backup folder with the timestamped name - mkdir "$backup_dir" - echo "Backup created successfully: $backup_dir" -} +echo "Backup Created: $PWD/$f_name" -# Function to perform the rotation and keep only the last 3 backups -function perform_rotation { - local backups=($(ls -t "${source_dir}/backup_"* 2>/dev/null)) # List existing backups sorted by timestamp +#deleting the files except the 3 latest backup files +rm -f $(ls -1t *.tar.gz | tail -n +4) - # Check if there are more than 3 backups - if [ "${#backups[@]}" -gt 3 ]; then - local backups_to_remove="${backups[@]:3}" # Get backups beyond the last 3 - rm -rf "${backups_to_remove[@]}" # Remove the oldest backups - fi -} - -# Main script logic -create_backup -perform_rotation diff --git a/Challenges/Day_2/explorer.sh b/Challenges/Day_2/explorer.sh index be62ca1..1868988 100644 --- a/Challenges/Day_2/explorer.sh +++ b/Challenges/Day_2/explorer.sh @@ -1,23 +1,22 @@ -#!/bin/bash +#!bin/bash/ -# Part 1: File and Directory Exploration echo "Welcome to the Interactive File and Directory Explorer!" -while true; do - # List all files and directories in the current path - echo "Files and Directories in the Current Path:" - ls -lh +#ls -lh will give us the list of files and directories with their size in human readable format +# awk will help us to print the 9th and 5th column of that output +echo "Files and Directories in the Current Path:" +ls -lh | awk '{print "-",$9,"(",$5,")"}' - # Part 2: Character Counting - read -p "Enter a line of text (Press Enter without text to exit): " input +#checking if the length of msg variable is 0, it will break out of the loop +while [ True ]; +do + read -p "Enter a line of text(Press enter without text to exit): " msg + if [ ${#msg} -eq 0 ] + then + break + fi + echo "Character Count: ${#msg} \n" +done - # Exit if the user enters an empty string - if [ -z "$input" ]; then - echo "Exiting the Interactive Explorer. Goodbye!" - break - fi +echo "Exiting the Interactive Explorer. Goodbye!" - # Calculate and print the character count for the input line - char_count=$(echo -n "$input" | wc -m) - echo "Character Count: $char_count" -done diff --git a/Challenges/Day_3/user_management.sh b/Challenges/Day_3/user_management.sh index 6f77f5d..a8d1651 100644 --- a/Challenges/Day_3/user_management.sh +++ b/Challenges/Day_3/user_management.sh @@ -1,94 +1,121 @@ #!/bin/bash -# Function to display usage information and available options -function display_usage { - echo "Usage: $0 [OPTIONS]" - echo "Options:" - echo " -c, --create Create a new user account." - echo " -d, --delete Delete an existing user account." - echo " -r, --reset Reset password for an existing user account." - echo " -l, --list List all user accounts on the system." - echo " -h, --help Display this help and exit." +#this will be called when the user inputs nothing, -h or --help +help(){ + echo "Usage: ./user_management.sh [OPTIONS]" + echo "Options:" + echo " -c, --create Create a new user account." + echo "-d, --delete Delete and existing user account." + echo "-r, --reset Reset password for an existing user account." + echo "-l, --list List all user accounts on the system." + echo "-h, --help Display this help and exit." } -# Function to create a new user account -function create_user { - read -p "Enter the new username: " username +#this will be called when the user inputs -c or --create +create(){ + read -p "Enter the new username: " username - # Check if the username already exists - if id "$username" &>/dev/null; then - echo "Error: The username '$username' already exists. Please choose a different username." - else - # Prompt for password (Note: You might want to use 'read -s' to hide the password input) - read -p "Enter the password for $username: " password + #this line will check if the user exists or not + a=`grep -w $username /etc/passwd` - # Create the user account - useradd -m -p "$password" "$username" - echo "User account '$username' created successfully." - fi -} - -# Function to delete an existing user account -function delete_user { - read -p "Enter the username to delete: " username + #the length of "a" will not be zero if the user already exists + if [ ${#a} -ne 0 ] + then echo "Error: The username $username already exists. Please choose a different username." + else + #this will create the user as the user doesnt exist + read -p "Enter the password for $username: " password + sudo useradd $username - # Check if the username exists - if id "$username" &>/dev/null; then - userdel -r "$username" # -r flag removes the user's home directory - echo "User account '$username' deleted successfully." - else - echo "Error: The username '$username' does not exist. Please enter a valid username." - fi + #this will give password to the command and any output will be not displayed on terminal + echo -e "$password\n$password" | sudo passwd $username 2>>/dev/null + echo "User account '$username' created successfully." + fi } -# Function to reset the password for an existing user account -function reset_password { - read -p "Enter the username to reset password: " username +#this will be called when the user inputs -d or --delete +delete(){ + read -p "Enter the username to delete: " uname_del - # Check if the username exists - if id "$username" &>/dev/null; then - # Prompt for password (Note: You might want to use 'read -s' to hide the password input) - read -p "Enter the new password for $username: " password + #this line will check if the user exists or not + a=`grep -w $uname_del /etc/passwd` + + #the length of "a" will not be zero if the user already exists + if [ ${#a} -eq 0 ] + then echo "Error: The username $uname_del doesn't exist. Please enter a valid username." + else + #this will delete the user as the user exists + sudo userdel $uname_del + echo "User account $uname_del deleted successfully" + fi +} - # Set the new password - echo "$username:$password" | chpasswd - echo "Password for user '$username' reset successfully." - else - echo "Error: The username '$username' does not exist. Please enter a valid username." - fi +#this will be called when the user inputs -r or --reset +reset(){ + read -p "Enter the username to reset password: " uname_res + + #this line will check if the user exists or not + a=`grep -w $uname_res /etc/passwd` + + #the length of "a" will not be zero if the user already exists + if [ ${#a} -eq 0 ] + then echo "Error: The username $uname_res doesn't exist. Please enter a valid username." + else + #this will reset the password of the user as the user exists + read -p "Enter the new password for $uname_res: " newp + echo -e "$newp\n$newp" | sudo passwd $uname_res 2>>/dev/null + echo "Password for user '$uname_res' reset successfully." + fi } -# Function to list all user accounts on the system -function list_users { - echo "User accounts on the system:" - cat /etc/passwd | awk -F: '{ print "- " $1 " (UID: " $3 ")" }' +#this will be called when the user inputs -l or --list +list(){ + #this will print the 1st and 3rd column from the /etc/passwd file with required formatting. + awk -F: '{print "- "$1,"(UID: "$3")"}' /etc/passwd } -# Check if no arguments are provided or if the -h or --help option is given -if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then - display_usage - exit 0 -fi +#we will use better than if-elif to call the functions based on the arguemnt passed +#in case, we can use "and" to combine conditions, i have written multiple times. +case "$1" in + "") + help + ;; + "-h") + help + ;; + "--help") + help + ;; + "--create") + create + ;; + "-c") + create + ;; + "--delete") + delete + + ;; + "-d") + delete + ;; + "--reset") + reset + ;; + "-r") + reset + ;; + "--list") + list + ;; + "-l") + list + ;; + *) + echo "This is not a valid option. Please check usage of this script below -" + help + ;; +esac + + -# Command-line argument parsing -while [ $# -gt 0 ]; do - case "$1" in - -c|--create) - create_user - ;; - -d|--delete) - delete_user - ;; - -r|--reset) - reset_password - ;; - -l|--list) - list_users - ;; - *) - echo "Error: Invalid option '$1'. Use '--help' to see available options." - exit 1 - ;; - esac - shift -done + diff --git a/Challenges/Day_4/Part_1_monitor_pro.md b/Challenges/Day_4/Part_1_monitor_pro.md index 7f80f8b..de13b8e 100644 --- a/Challenges/Day_4/Part_1_monitor_pro.md +++ b/Challenges/Day_4/Part_1_monitor_pro.md @@ -1,59 +1,59 @@ -# BashBlaze Scripting Challenge - Day 4 - -Welcome to the Bash Scripting Challenge - Day 4! This challenge is designed to test your Bash scripting skills and problem-solving abilities in the context of process monitoring and management. - -## Scenario - -You are tasked with writing a Bash script that efficiently monitors a specific process on a Linux system. The script's primary goal is to ensure the process is always running, and if it unexpectedly stops, it should be restarted automatically. - -## Task - -1. **Process Selection:** - - - The script should accept a command-line argument to specify the target process to monitor. For example: `./monitor_process.sh `. - -2. **Process Existence Check:** - - - Implement a function that checks if the specified process is currently running on the system. - - If the process is running, print a message indicating its presence. - -3. **Restarting the Process:** - - - If the process is not running, implement a function that attempts to restart the process automatically. - - Print a message indicating the attempt to restart the process. - - Ensure the script does not enter an infinite loop while restarting the process. Limit the number of restart attempts. - -4. **Automation:** - - - Provide instructions on how to schedule the script to run at regular intervals using a cron job or any other appropriate scheduling method. - -5. **Documentation:** - - - Include clear and concise comments in the script to explain its logic and functionality. - - Write a separate document describing the purpose of the script, how to use it, and any specific considerations. - -6. **Bonus:** - - Implement a notification mechanism (e.g., email, Slack message) to alert administrators if the process requires manual intervention after a certain number of restart attempts. - -Remember to test your script thoroughly on a test system before deploying it to a production environment. Ensure it does not interfere with critical processes or cause any unintended side effects. Consider edge cases and potential race conditions during process monitoring and restarting. - -## Example Interaction - -Check the [example_interaction.md](./usr_example_interaction.md) -file to see a sample interaction with the script, demonstrating its usage and behavior. - -## Submission Guidelines - -1. Fork this repository to your GitHub account. -2. Implement the Bash script according to the provided scenario and tasks. -3. Create a new branch in your forked repository for your changes. -4. Commit your changes with meaningful commit messages. -5. Push your changes to your forked repository. -6. Create a pull request from your branch to the original repository. - -## Notes - -- You can customize the script, add more features, or enhance the error handling as you see fit. -- If you encounter any issues or have questions, feel free to open an issue in this repository. - -Happy scripting and good luck with the challenge! +# BashBlaze Scripting Challenge - Day 4 + +Welcome to the Bash Scripting Challenge - Day 4! This challenge is designed to test your Bash scripting skills and problem-solving abilities in the context of process monitoring and management. + +## Scenario + +You are tasked with writing a Bash script that efficiently monitors a specific process on a Linux system. The script's primary goal is to ensure the process is always running, and if it unexpectedly stops, it should be restarted automatically. + +## Task + +1. **Process Selection:** + + - The script should accept a command-line argument to specify the target process to monitor. For example: `./monitor_process.sh `. + +2. **Process Existence Check:** + + - Implement a function that checks if the specified process is currently running on the system. + - If the process is running, print a message indicating its presence. + +3. **Restarting the Process:** + + - If the process is not running, implement a function that attempts to restart the process automatically. + - Print a message indicating the attempt to restart the process. + - Ensure the script does not enter an infinite loop while restarting the process. Limit the number of restart attempts. + +4. **Automation:** + + - Provide instructions on how to schedule the script to run at regular intervals using a cron job or any other appropriate scheduling method. + +5. **Documentation:** + + - Include clear and concise comments in the script to explain its logic and functionality. + - Write a separate document describing the purpose of the script, how to use it, and any specific considerations. + +6. **Bonus:** + - Implement a notification mechanism (e.g., email, Slack message) to alert administrators if the process requires manual intervention after a certain number of restart attempts. + +Remember to test your script thoroughly on a test system before deploying it to a production environment. Ensure it does not interfere with critical processes or cause any unintended side effects. Consider edge cases and potential race conditions during process monitoring and restarting. + +## Example Interaction + +Check the [example_interaction.md](./usr_example_interaction.md) +file to see a sample interaction with the script, demonstrating its usage and behavior. + +## Submission Guidelines + +1. Fork this repository to your GitHub account. +2. Implement the Bash script according to the provided scenario and tasks. +3. Create a new branch in your forked repository for your changes. +4. Commit your changes with meaningful commit messages. +5. Push your changes to your forked repository. +6. Create a pull request from your branch to the original repository. + +## Notes + +- You can customize the script, add more features, or enhance the error handling as you see fit. +- If you encounter any issues or have questions, feel free to open an issue in this repository. + +Happy scripting and good luck with the challenge! diff --git a/Challenges/Day_4/Part_2_Monitoring_Metrics.md b/Challenges/Day_4/Part_2_Monitoring_Metrics.md index 13e2629..1dadd9d 100644 --- a/Challenges/Day_4/Part_2_Monitoring_Metrics.md +++ b/Challenges/Day_4/Part_2_Monitoring_Metrics.md @@ -1,43 +1,43 @@ -# Monitoring Metrics Script with Sleep Mechanism - -## Challenge Description - -This project aims to create a Bash script that monitors system metrics like CPU usage, memory usage, and disk space usage. The script will provide a user-friendly interface, allow continuous monitoring with a specified sleep interval, and extend its capabilities to monitor specific services like Nginx. - -## Tasks - -### Task 1: Implementing Basic Metrics Monitoring - -Write a Bash script that monitors the CPU usage, memory usage, and disk space usage of the system. The script should display these metrics in a clear and organized manner, allowing users to interpret the data easily. The script should use the top, free, and df commands to fetch the metrics. - -### Task 2: User-Friendly Interface - -Enhance the script by providing a user-friendly interface that allows users to interact with the script through the terminal. Display a simple menu with options to view the metrics and an option to exit the script. - -### Task 3: Continuous Monitoring with Sleep - -Introduce a loop in the script to allow continuous monitoring until the user chooses to exit. After displaying the metrics, add a "sleep" mechanism to pause the monitoring for a specified interval before displaying the metrics again. Allow the user to specify the sleep interval. - -### Task 4: Monitoring a Specific Service (e.g., Nginx) - -Extend the script to monitor a specific service like Nginx. Check if the service is running and display its status. If it is not running, provide an option for the user to start the service. Use the systemctl or appropriate command to check and control the service. - -### Task 5: Allow User to Choose a Different Service - -Modify the script to give the user the option to monitor a different service of their choice. Prompt the user to enter the name of the service they want to monitor, and display its status accordingly. - -### Task 6: Error Handling - -Implement error handling in the script to handle scenarios where commands fail or inputs are invalid. Display meaningful error messages to guide users on what went wrong and how to fix it. - -### Task 7: Documentation - -Add comments within the script to explain the purpose of each function, variable, and section of the code. Provide a clear and concise README file explaining how to use the script, the available options, and the purpose of the script. - -Remember, the main goal of this challenge is to utilize various monitoring commands, implement a user-friendly interface, and create a script that is easy to understand and use. - -Feel free to explore and research relevant commands and syntax while completing the tasks.Enjoy monitoring your system metrics effortlessly - -## You can also check out the [interactive monitoring Metrics script repository](./usr_interaction_with_metrics.md) to see the code in action. - ->>This project is an excellent addition to your portfolio. I can't wait to see what creative names you've given to this script. +# Monitoring Metrics Script with Sleep Mechanism + +## Challenge Description + +This project aims to create a Bash script that monitors system metrics like CPU usage, memory usage, and disk space usage. The script will provide a user-friendly interface, allow continuous monitoring with a specified sleep interval, and extend its capabilities to monitor specific services like Nginx. + +## Tasks + +### Task 1: Implementing Basic Metrics Monitoring + +Write a Bash script that monitors the CPU usage, memory usage, and disk space usage of the system. The script should display these metrics in a clear and organized manner, allowing users to interpret the data easily. The script should use the top, free, and df commands to fetch the metrics. + +### Task 2: User-Friendly Interface + +Enhance the script by providing a user-friendly interface that allows users to interact with the script through the terminal. Display a simple menu with options to view the metrics and an option to exit the script. + +### Task 3: Continuous Monitoring with Sleep + +Introduce a loop in the script to allow continuous monitoring until the user chooses to exit. After displaying the metrics, add a "sleep" mechanism to pause the monitoring for a specified interval before displaying the metrics again. Allow the user to specify the sleep interval. + +### Task 4: Monitoring a Specific Service (e.g., Nginx) + +Extend the script to monitor a specific service like Nginx. Check if the service is running and display its status. If it is not running, provide an option for the user to start the service. Use the systemctl or appropriate command to check and control the service. + +### Task 5: Allow User to Choose a Different Service + +Modify the script to give the user the option to monitor a different service of their choice. Prompt the user to enter the name of the service they want to monitor, and display its status accordingly. + +### Task 6: Error Handling + +Implement error handling in the script to handle scenarios where commands fail or inputs are invalid. Display meaningful error messages to guide users on what went wrong and how to fix it. + +### Task 7: Documentation + +Add comments within the script to explain the purpose of each function, variable, and section of the code. Provide a clear and concise README file explaining how to use the script, the available options, and the purpose of the script. + +Remember, the main goal of this challenge is to utilize various monitoring commands, implement a user-friendly interface, and create a script that is easy to understand and use. + +Feel free to explore and research relevant commands and syntax while completing the tasks.Enjoy monitoring your system metrics effortlessly + +## You can also check out the [interactive monitoring Metrics script repository](./usr_interaction_with_metrics.md) to see the code in action. + +>>This project is an excellent addition to your portfolio. I can't wait to see what creative names you've given to this script. diff --git a/Challenges/Day_4/Welcome to the Bash Scripting Challenge.docx b/Challenges/Day_4/Welcome to the Bash Scripting Challenge.docx new file mode 100644 index 0000000..47f8d36 Binary files /dev/null and b/Challenges/Day_4/Welcome to the Bash Scripting Challenge.docx differ diff --git a/Challenges/Day_4/monitor_process.sh b/Challenges/Day_4/monitor_process.sh new file mode 100644 index 0000000..481c0eb --- /dev/null +++ b/Challenges/Day_4/monitor_process.sh @@ -0,0 +1,74 @@ +#!/bin/bash + +#storing the service name +serv=$1 +if [ ${#1} -eq 0 ] +then + echo "Please enter a service name after the bash filename." +fi + +restart_serv(){ + + serv_active_restart=`sudo systemctl is-active $1` + case "$serv_active_restart" in + active) + #this will get printed in the 2nd or 3rd try if it wasn't running in the 1st or 2nd try + echo "Process $1 is running." + ;; + failed|inactive) + echo "Process $1 is not running. Attempting to restart..." + + #this will restart the process. + sudo systemctl restart nginx.service + + #if the process is activated, this will print this statement. + if [ `sudo systemctl is-active $1`=="active" ] + then + echo "Process $1 restarted successfully." + fi + ;; + *) + esac +} + +#if user has entered something +if [ ${#1} -ne 0 ] +then + +#this will check if the service is present in system +#we will get nothing if the service is not present +a=`systemctl list-unit-files --type service | grep -F $1` + + +if [ ${#a} -eq 0 ] +then + echo "The process '$1' doesn't exist." +else + #this will check if process is active or not + serv_active=`sudo systemctl is-active $1` + case "$serv_active" in + active) + echo "Process $1 is running." + ;; + failed|inactive) + #if process is not active, we will try to restart it 3 times + for i in {1..3} + do + restart_serv $1 + done + ;; + *) + esac + + #this will be used to check the status of process after the 3 attempts + serv_active_r=`sudo systemctl is-active $1` + + #if the process is still not active, we will tell to do it manually + case "$serv_active_r" in + failed|inactive) + echo "Maximum restart attempts reached. Please check the process manually." + ;; + *) + esac +fi +fi diff --git a/Challenges/Day_4/monitoring_script.sh b/Challenges/Day_4/monitoring_script.sh new file mode 100644 index 0000000..d370319 --- /dev/null +++ b/Challenges/Day_4/monitoring_script.sh @@ -0,0 +1,120 @@ +#!/bin/bash + +#this will print the menu +metrics(){ + echo "" + echo "---Monitoring Metrics Script---" + echo "1. View system metrics" + echo "2. Monitor a specific service" + echo "3. Exit" + echo "" +} + +first(){ + + #this will calculate the system's cpu usage + cpu_usage=`top -bn2 | grep '%Cpu' | tail -1 | grep -P '(....|...) id,'| awk '{print 100-$8}'` + + #this will calculate the system's memory usage + mem_usage=`free | grep "Mem" | awk '{print 100*$3/$2}'` + + #this will calculate the usage of the volume we have mounted(shared directory) + disk_usage=`df | grep dtworkspace | awk '{print 100*$4/$3}'` + + echo "CPU Usage : $cpu_usage% Mem usage: $mem_usage% Disk Space: $disk_usage%" + #read -p "Press enter to continue: " opt + sleep_mech +} + +sleep_mech(){ + #we will ask how much seconds to wait before we get the updated usage details + echo "" + read -p "How much seconds would you like to wait before displaying the updated usage details? " sl + if [ ${#sl} -eq 0 ] + then + read -p "Press enter to continue: " opt + else + sleep $sl + first + fi +} + + +start_ser(){ + case "$2" in + Y) + #if the user wants to restart the service, this will get executed. + sudo systemctl restart nginx.service + if [ `sudo systemctl is-active $1`=="active" ] + then + echo "$1 restarted successfully." + else + echo "$1 couldn't be restarted." + fi + ;; + N) + #if the user doesnt want to restart the service, this will get executed. + echo "We didn't restart $1" + ;; + *) + esac +} + + +second(){ + echo "---Monitor a specific service---" + read -p "Enter the name of the service to monitor: " service_name + + #this will check if the service is present in system + #we will get nothing if the service is not present + a=`systemctl list-unit-files --type service | grep -F $service_name` + + if [ ${#a} -eq 0 ] + then + echo "The process '$service_name' doesn't exist." + else + + #if the process exists, this will get executed. + echo "---$service_name Status---" + + #checking if the process is active or not + serv_active=`sudo systemctl is-active $service_name` + case "$serv_active" in + active) + echo "$service_name is running." + ;; + failed|inactive) + echo "$service_name is not running." + read -p "Do you want to start $service_name? (Y/N): " ans + start_ser $service_name $ans + ;; + *) + esac + fi + read -p "Press enter to continue: " opt +} + +third(){ + exit 0 +} + +while [ true ] +do + metrics + read -p "Enter the selection: " opt + echo "" + case "$opt" in + 1) + first + ;; + 2) + second + ;; + 3) + third + ;; + *) + echo "This is an invalid option." + ;; +esac +done diff --git a/Challenges/Day_4/usr_example_interaction.md b/Challenges/Day_4/usr_example_interaction.md index 4e9d5c9..06910ad 100644 --- a/Challenges/Day_4/usr_example_interaction.md +++ b/Challenges/Day_4/usr_example_interaction.md @@ -1,70 +1,70 @@ -# Example Interaction - Monitoring Nginx Process - -In this example, we will demonstrate the usage of the `monitor_process.sh` script to monitor the Nginx process on a Linux system. The script will check if the Nginx process is running and restart it if it's not. - -## Prerequisites - -Before proceeding, make sure you have the following: - -- A Linux-based system (Ubuntu, CentOS, etc.) with Nginx installed. - -> Assuming the script is saved as monitor_process.sh, and the process to monitor is Nginx. - -1. Execute the monitor_process.sh script with "nginx" as the process name to monitor: - -``` -./monitor_process.sh nginx -``` - -The script will check if the Nginx process is running and provide appropriate output based on its status. - -2. Simulate Nginx Process Stopping - -For demonstration purposes, let's simulate the Nginx process stopping. You can stop the Nginx service using the following command: - -``` -sudo systemctl stop nginx -``` - -3. Monitor the Nginx Process - -Now, let's run the monitor_process.sh script again to see how it automatically restarts the Nginx process: - -The script will detect that the Nginx process is not running and attempt to restart it. It will display messages indicating the attempt to restart the process. - -The script will attempt to restart the process automatically for three times: - -``` -Process Nginx is not running. Attempting to restart... -Process Nginx is not running. Attempting to restart... -Process Nginx is not running. Attempting to restart... -Maximum restart attempts reached. Please check the process manually. - -``` - -4. Check Nginx Status - -After the script attempts to restart the Nginx process, you can verify its status using the following command: - -``` -sudo systemctl status nginx -``` - -"You should see that the Nginx process is **now running**." - -5. Automation (Optional) - To automate the process monitoring, you can set up a cron job to run the script at regular intervals. - - - - -------------------------------------------------------------------------------------------------------------------------------------------- - - - - -![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/4939241c-66f7-4445-bab5-6e8e8faa9d3f) - -------------------------------------------------------------------------------------------------------------------------------------------- - -![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/b54073b7-2ba6-4727-8d74-bb64a25b273e) +# Example Interaction - Monitoring Nginx Process + +In this example, we will demonstrate the usage of the `monitor_process.sh` script to monitor the Nginx process on a Linux system. The script will check if the Nginx process is running and restart it if it's not. + +## Prerequisites + +Before proceeding, make sure you have the following: + +- A Linux-based system (Ubuntu, CentOS, etc.) with Nginx installed. + +> Assuming the script is saved as monitor_process.sh, and the process to monitor is Nginx. + +1. Execute the monitor_process.sh script with "nginx" as the process name to monitor: + +``` +./monitor_process.sh nginx +``` + +The script will check if the Nginx process is running and provide appropriate output based on its status. + +2. Simulate Nginx Process Stopping + +For demonstration purposes, let's simulate the Nginx process stopping. You can stop the Nginx service using the following command: + +``` +sudo systemctl stop nginx +``` + +3. Monitor the Nginx Process + +Now, let's run the monitor_process.sh script again to see how it automatically restarts the Nginx process: + +The script will detect that the Nginx process is not running and attempt to restart it. It will display messages indicating the attempt to restart the process. + +The script will attempt to restart the process automatically for three times: + +``` +Process Nginx is not running. Attempting to restart... +Process Nginx is not running. Attempting to restart... +Process Nginx is not running. Attempting to restart... +Maximum restart attempts reached. Please check the process manually. + +``` + +4. Check Nginx Status + +After the script attempts to restart the Nginx process, you can verify its status using the following command: + +``` +sudo systemctl status nginx +``` + +"You should see that the Nginx process is **now running**." + +5. Automation (Optional) + To automate the process monitoring, you can set up a cron job to run the script at regular intervals. + + + + +------------------------------------------------------------------------------------------------------------------------------------------- + + + + +![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/4939241c-66f7-4445-bab5-6e8e8faa9d3f) + +------------------------------------------------------------------------------------------------------------------------------------------- + +![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/b54073b7-2ba6-4727-8d74-bb64a25b273e) diff --git a/Challenges/Day_4/usr_interaction_with_metrics.md b/Challenges/Day_4/usr_interaction_with_metrics.md index 541d2ff..e9efe76 100644 --- a/Challenges/Day_4/usr_interaction_with_metrics.md +++ b/Challenges/Day_4/usr_interaction_with_metrics.md @@ -1,105 +1,105 @@ ---- - -## Monitoring Metrics Script - User Interaction Example - -Assume we have a script called `monitoring_script.sh` that implements the tasks mentioned in the challenge. - -1. **Launching the Script** - - Open a terminal and navigate to the directory where `monitoring_script.sh` is located. Execute the script using the following command: - - ```bash - $ ./monitoring_script.sh - ``` - -2. **Main Menu** - - Once the script starts, you'll see a simple menu displayed on the terminal: - - ``` - ---- Monitoring Metrics Script ---- - - 1. View System Metrics - 2. Monitor a Specific Service - 3. Exit - ``` - -3. **View System Metrics** - - If you choose option 1, the script will display the current system metrics, including CPU usage, memory usage, and disk space usage. The output might look like this: - - ``` - ---- System Metrics ---- - - CPU Usage: 8% Mem Usage: 24% Disk Space: 62% - - Press Enter to continue... - ``` - - The script waits for a moment (based on the specified sleep interval) before displaying the metrics again. - -4. **Monitor a Specific Service** - - If you choose option 2, the script will prompt you to enter the name of the service you want to monitor. Let's say you want to monitor Nginx. Enter "nginx" when prompted: - - ``` - ---- Monitor a Specific Service ---- - - Enter the name of the service to monitor: nginx - ``` - - The script will check the status of Nginx and display whether it is running or not: - - ``` - ---- Nginx Status ---- - - Nginx is running. - - Press Enter to continue... - ``` - - If Nginx is not running, you'll see: - - ``` - ---- Nginx Status ---- - - Nginx is not running. - - Do you want to start Nginx? (Y/N): _ - ``` - - If you choose "Y," the script will attempt to start Nginx. - -5. **Exit** - - If you choose option 3, the script will gracefully exit, and the terminal prompt will be returned to you. - -6. **Error Handling** - - In case of any errors, such as invalid input or failed commands, the script will display appropriate error messages. For example: - - ``` - Error: Invalid option. Please choose a valid option (1, 2, or 3). - ``` - ---- - -Note: The above example assumes that the script is implemented according to the tasks mentioned in the challenge. - -### Get Help and Stay Connected - -If you have any questions or need assistance during the challenge, feel free to connect with me on LinkedIn. Click the button below to visit my profile: - -[![LinkedIn Profile](../../assets/icons8-linkedin-96(@2x).png)](https://www.linkedin.com/in/d-prajwal/) - -### Reference Videos - -If you are new to bash scripting or need some helpful resources, check out these reference videos for beginners: - -1. [EASIEST Shell Scripting Tutorial for Beginners](https://youtu.be/_-D6gkRj7xc) -2. [ADVANCED Shell Scripting Tutorial](https://youtu.be/UYstAfqkLtg) -3. [New ADVANCED Shell Scripting Tutorial for DevOps](https://youtu.be/IoUGl76kyLk) - -These videos will give you a solid foundation in bash scripting and help you tackle this challenge with confidence. - -Happy scripting and best of luck with the challenge! Don't hesitate to reach out if you need any assistance. Let's make this challenge a great learning experience together! +--- + +## Monitoring Metrics Script - User Interaction Example + +Assume we have a script called `monitoring_script.sh` that implements the tasks mentioned in the challenge. + +1. **Launching the Script** + + Open a terminal and navigate to the directory where `monitoring_script.sh` is located. Execute the script using the following command: + + ```bash + $ ./monitoring_script.sh + ``` + +2. **Main Menu** + + Once the script starts, you'll see a simple menu displayed on the terminal: + + ``` + ---- Monitoring Metrics Script ---- + + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + ``` + +3. **View System Metrics** + + If you choose option 1, the script will display the current system metrics, including CPU usage, memory usage, and disk space usage. The output might look like this: + + ``` + ---- System Metrics ---- + + CPU Usage: 8% Mem Usage: 24% Disk Space: 62% + + Press Enter to continue... + ``` + + The script waits for a moment (based on the specified sleep interval) before displaying the metrics again. + +4. **Monitor a Specific Service** + + If you choose option 2, the script will prompt you to enter the name of the service you want to monitor. Let's say you want to monitor Nginx. Enter "nginx" when prompted: + + ``` + ---- Monitor a Specific Service ---- + + Enter the name of the service to monitor: nginx + ``` + + The script will check the status of Nginx and display whether it is running or not: + + ``` + ---- Nginx Status ---- + + Nginx is running. + + Press Enter to continue... + ``` + + If Nginx is not running, you'll see: + + ``` + ---- Nginx Status ---- + + Nginx is not running. + + Do you want to start Nginx? (Y/N): _ + ``` + + If you choose "Y," the script will attempt to start Nginx. + +5. **Exit** + + If you choose option 3, the script will gracefully exit, and the terminal prompt will be returned to you. + +6. **Error Handling** + + In case of any errors, such as invalid input or failed commands, the script will display appropriate error messages. For example: + + ``` + Error: Invalid option. Please choose a valid option (1, 2, or 3). + ``` + +--- + +Note: The above example assumes that the script is implemented according to the tasks mentioned in the challenge. + +### Get Help and Stay Connected + +If you have any questions or need assistance during the challenge, feel free to connect with me on LinkedIn. Click the button below to visit my profile: + +[![LinkedIn Profile](../../assets/icons8-linkedin-96(@2x).png)](https://www.linkedin.com/in/d-prajwal/) + +### Reference Videos + +If you are new to bash scripting or need some helpful resources, check out these reference videos for beginners: + +1. [EASIEST Shell Scripting Tutorial for Beginners](https://youtu.be/_-D6gkRj7xc) +2. [ADVANCED Shell Scripting Tutorial](https://youtu.be/UYstAfqkLtg) +3. [New ADVANCED Shell Scripting Tutorial for DevOps](https://youtu.be/IoUGl76kyLk) + +These videos will give you a solid foundation in bash scripting and help you tackle this challenge with confidence. + +Happy scripting and best of luck with the challenge! Don't hesitate to reach out if you need any assistance. Let's make this challenge a great learning experience together! diff --git a/Challenges/Day_5/DAY_6_Document.pdf b/Challenges/Day_5/DAY_6_Document.pdf new file mode 100644 index 0000000..6716ce2 Binary files /dev/null and b/Challenges/Day_5/DAY_6_Document.pdf differ diff --git a/Challenges/Day_5/Log_Analyzer.md b/Challenges/Day_5/Log_Analyzer.md index 527814d..c8f0c7e 100644 --- a/Challenges/Day_5/Log_Analyzer.md +++ b/Challenges/Day_5/Log_Analyzer.md @@ -1,56 +1,56 @@ -# Day 5: Bash Scripting Challenge - Log Analyzer and Report Generator - -## Challenge Title: Log Analyzer and Report Generator - -## Scenario - -You are a system administrator responsible for managing a network of servers. Every day, a log file is generated on each server containing important system events and error messages. As part of your daily tasks, you need to analyze these log files, identify specific events, and generate a summary report. - -## Task - -Write a Bash script that automates the process of analyzing log files and generating a daily summary report. The script should perform the following steps: - -1. **Input:** The script should take the path to the log file as a command-line argument. - -2. **Error Count:** Analyze the log file and count the number of error messages. An error message can be identified by a specific keyword (e.g., "ERROR" or "Failed"). Print the total error count. - -3. **Critical Events:** Search for lines containing the keyword "CRITICAL" and print those lines along with the line number. - -4. **Top Error Messages:** Identify the top 5 most common error messages and display them along with their occurrence count. - -5. **Summary Report:** Generate a summary report in a separate text file. The report should include: - - - Date of analysis - - Log file name - - Total lines processed - - Total error count - - Top 5 error messages with their occurrence count - - List of critical events with line numbers - -6. **Optional Enhancement:** Add a feature to automatically archive or move processed log files to a designated directory after analysis. - -## Tips - -- Use `grep`, `awk`, and other command-line tools to process the log file. -- Utilize arrays or associative arrays to keep track of error messages and their counts. -- Use appropriate error handling to handle cases where the log file doesn't exist or other issues arise. - -## Sample Log File - -A sample log file named `sample_log.log` has been provided in the same directory as this challenge file. You can use this file to test your script. - -## How to Participate - -1. Clone this repository or download the challenge file from the provided link. -2. Write your Bash script to complete the log analyzer and report generator task. -3. Use the provided `sample_log.log` or create your own log files for testing. -4. Test your script with various log files and scenarios to ensure accuracy. -5. Submit your completed script by the end of Day 5 of the 7-day Bash scripting challenge. - -## Submission - -Submit your completed script by [creating a pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) or sending the script file to the challenge organizer. - -Good luck and happy scripting! - ---- +# Day 5: Bash Scripting Challenge - Log Analyzer and Report Generator + +## Challenge Title: Log Analyzer and Report Generator + +## Scenario + +You are a system administrator responsible for managing a network of servers. Every day, a log file is generated on each server containing important system events and error messages. As part of your daily tasks, you need to analyze these log files, identify specific events, and generate a summary report. + +## Task + +Write a Bash script that automates the process of analyzing log files and generating a daily summary report. The script should perform the following steps: + +1. **Input:** The script should take the path to the log file as a command-line argument. + +2. **Error Count:** Analyze the log file and count the number of error messages. An error message can be identified by a specific keyword (e.g., "ERROR" or "Failed"). Print the total error count. + +3. **Critical Events:** Search for lines containing the keyword "CRITICAL" and print those lines along with the line number. + +4. **Top Error Messages:** Identify the top 5 most common error messages and display them along with their occurrence count. + +5. **Summary Report:** Generate a summary report in a separate text file. The report should include: + + - Date of analysis + - Log file name + - Total lines processed + - Total error count + - Top 5 error messages with their occurrence count + - List of critical events with line numbers + +6. **Optional Enhancement:** Add a feature to automatically archive or move processed log files to a designated directory after analysis. + +## Tips + +- Use `grep`, `awk`, and other command-line tools to process the log file. +- Utilize arrays or associative arrays to keep track of error messages and their counts. +- Use appropriate error handling to handle cases where the log file doesn't exist or other issues arise. + +## Sample Log File + +A sample log file named `sample_log.log` has been provided in the same directory as this challenge file. You can use this file to test your script. + +## How to Participate + +1. Clone this repository or download the challenge file from the provided link. +2. Write your Bash script to complete the log analyzer and report generator task. +3. Use the provided `sample_log.log` or create your own log files for testing. +4. Test your script with various log files and scenarios to ensure accuracy. +5. Submit your completed script by the end of Day 5 of the 7-day Bash scripting challenge. + +## Submission + +Submit your completed script by [creating a pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) or sending the script file to the challenge organizer. + +Good luck and happy scripting! + +--- diff --git a/Challenges/Day_5/Sample_Log_Data.md b/Challenges/Day_5/Sample_Log_Data.md index 3ddc8a6..d2f61b7 100644 --- a/Challenges/Day_5/Sample_Log_Data.md +++ b/Challenges/Day_5/Sample_Log_Data.md @@ -1,77 +1,77 @@ -# Welcome, Challenger! - -## Sample Log Data for Testing - -Congratulations on reaching Day 5 of the 7-day Bash scripting challenge! To assist you in testing your log analyzer and report generator script, we have something below. - -## Create Your Own Data - -Feeling adventurous? If you want to go beyond the provided sample data(which you won't find because i haven't uploaded it ), you can generate your own log data using the `log_generator.sh` script. This script allows you to create log files with custom log levels, error messages, and line counts. - -**How to Generate Your Own Log Data:** - -1. Execute the `log_generator.sh` script with the desired log file path and the number of lines you want to generate. -2. Customize the `log_levels` and `error_messages` arrays in the script to tailor the log data to your needs. - -Remember, the more diverse log data you test with, the better you can fine-tune your script! - -Wishing you the best of luck in this challenge. Happy scripting! - ---- - -```Bash -#!/bin/bash - -# Usage: ./log_generator.sh - -if [ "$#" -ne 2 ]; then - echo "Usage: $0 " - exit 1 -fi - -log_file_path="$1" -num_lines="$2" - -if [ -e "$log_file_path" ]; then - echo "Error: File already exists at $log_file_path." - exit 1 -fi - -# List of possible log message levels -log_levels=("INFO" "DEBUG" "ERROR" "WARNING" "CRITICAL") - -# List of possible error messages -error_messages=("Failed to connect" "Disk full" "Segmentation fault" "Invalid input" "Out of memory") - -# Function to generate a random log line -generate_log_line() { - local log_level="${log_levels[$((RANDOM % ${#log_levels[@]}))]}" - local error_msg="" - if [ "$log_level" == "ERROR" ]; then - error_msg="${error_messages[$((RANDOM % ${#error_messages[@]}))]}" - fi - echo "$(date '+%Y-%m-%d %H:%M:%S') [$log_level] $error_msg - $RANDOM" -} - -# Create the log file with random log lines -touch "$log_file_path" -for ((i=0; i> "$log_file_path" -done - -echo "Log file created at: $log_file_path with $num_lines lines." - -``` - ---- - -Usage: -To use the log generator script, participants can execute the following command: - -``` -./log_generator.sh /path/to/logfile.log 100 -``` - -> This will create a log file named "logfile.log" in the specified path with 100 random log lines. Participants can adjust the number of lines as needed for testing their log analyzer and report generator scripts. - -The log lines generated will have timestamps, log levels (INFO, DEBUG, ERROR, WARNING, CRITICAL), and randomly chosen error messages for lines with "ERROR" log level. +# Welcome, Challenger! + +## Sample Log Data for Testing + +Congratulations on reaching Day 5 of the 7-day Bash scripting challenge! To assist you in testing your log analyzer and report generator script, we have something below. + +## Create Your Own Data + +Feeling adventurous? If you want to go beyond the provided sample data(which you won't find because i haven't uploaded it ), you can generate your own log data using the `log_generator.sh` script. This script allows you to create log files with custom log levels, error messages, and line counts. + +**How to Generate Your Own Log Data:** + +1. Execute the `log_generator.sh` script with the desired log file path and the number of lines you want to generate. +2. Customize the `log_levels` and `error_messages` arrays in the script to tailor the log data to your needs. + +Remember, the more diverse log data you test with, the better you can fine-tune your script! + +Wishing you the best of luck in this challenge. Happy scripting! + +--- + +```Bash +#!/bin/bash + +# Usage: ./log_generator.sh + +if [ "$#" -ne 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +log_file_path="$1" +num_lines="$2" + +if [ -e "$log_file_path" ]; then + echo "Error: File already exists at $log_file_path." + exit 1 +fi + +# List of possible log message levels +log_levels=("INFO" "DEBUG" "ERROR" "WARNING" "CRITICAL") + +# List of possible error messages +error_messages=("Failed to connect" "Disk full" "Segmentation fault" "Invalid input" "Out of memory") + +# Function to generate a random log line +generate_log_line() { + local log_level="${log_levels[$((RANDOM % ${#log_levels[@]}))]}" + local error_msg="" + if [ "$log_level" == "ERROR" ]; then + error_msg="${error_messages[$((RANDOM % ${#error_messages[@]}))]}" + fi + echo "$(date '+%Y-%m-%d %H:%M:%S') [$log_level] $error_msg - $RANDOM" +} + +# Create the log file with random log lines +touch "$log_file_path" +for ((i=0; i> "$log_file_path" +done + +echo "Log file created at: $log_file_path with $num_lines lines." + +``` + +--- + +Usage: +To use the log generator script, participants can execute the following command: + +``` +./log_generator.sh /path/to/logfile.log 100 +``` + +> This will create a log file named "logfile.log" in the specified path with 100 random log lines. Participants can adjust the number of lines as needed for testing their log analyzer and report generator scripts. + +The log lines generated will have timestamps, log levels (INFO, DEBUG, ERROR, WARNING, CRITICAL), and randomly chosen error messages for lines with "ERROR" log level. diff --git a/Challenges/Day_5/log_analyzer.sh b/Challenges/Day_5/log_analyzer.sh index 70779dc..9803276 100644 --- a/Challenges/Day_5/log_analyzer.sh +++ b/Challenges/Day_5/log_analyzer.sh @@ -1,56 +1,40 @@ #!/bin/bash - -# Check if the user provided the log file path as a command-line argument -if [ $# -ne 1 ]; then - echo "Usage: $0 " - exit 1 -fi - -# Get the log file path from the command-line argument -log_file="$1" - -# Check if the log file exists -if [ ! -f "$log_file" ]; then - echo "Error: Log file not found: $log_file" - exit 1 +if [ ${#1} -eq 0 ] +then + echo "Please enter a log file name" + echo "Usage: ./log_analyzer.sh log_file.txt" +else + file=$1 + if [ -f "$file" ]; + then + i=1 + no_of_error=0 + date_of_analysis=$(date '+%Y-%m-%d_%H-%M-%S') + lines=`cat $file | wc -l` + no_of_error=`cat $file | grep -E "ERROR|FAILED" | wc -l` + top_error=`cat $file | awk -F'] |- ' '{print $2}' | sort | uniq -c | sort -nr | head -n 6 | tail -n 5` + + echo "Date of analysis: $date_of_analysis" > report.txt + echo "Log file name: $file" >> report.txt + echo "Total lines processed: $lines" >> report.txt + echo "Total error count: $no_of_error" >> report.txt + echo "Top 5 error messages with their occurrence count: " >> report.txt + echo "$top_error" >> report.txt + echo "List of critical events with line numbers: " >> report.txt + while read line; do + if [[ $line == *"CRITICAL"* ]]; then + echo "Line No. $i : $line" >> report.txt + fi + i=$((i+1)) + done < $file + dest_path="logs_archive" + mv $file "$date_of_analysis""_log.txt" + file="$date_of_analysis""_log.txt" + mkdir -p $dest_path + mv $file $dest_path + echo "Log has been analyzed and the report is generated" + else + echo "This file doesn't exist." + echo "Please enter a proper file name" + fi fi - -# Step 1: Count the total number of lines in the log file -total_lines=$(wc -l < "$log_file") - -# Step 2: Count the number of error messages (identified by the keyword "ERROR" in this example) -error_count=$(grep -c -i "ERROR" "$log_file") - -# Step 3: Search for critical events (lines containing the keyword "CRITICAL") and store them in an array -mapfile -t critical_events < <(grep -n -i "CRITICAL" "$log_file") - -# Step 4: Identify the top 5 most common error messages and their occurrence count using associative arrays -declare -A error_messages -while IFS= read -r line; do - # Use awk to extract the error message (fields are space-separated) - error_msg=$(awk '{for (i=3; i<=NF; i++) printf $i " "; print ""}' <<< "$line") - ((error_messages["$error_msg"]++)) -done < <(grep -i "ERROR" "$log_file") - -# Sort the error messages by occurrence count (descending order) -sorted_error_messages=$(for key in "${!error_messages[@]}"; do - echo "${error_messages[$key]} $key" -done | sort -rn | head -n 5) - -# Step 5: Generate the summary report in a separate file -summary_report="log_summary_$(date +%Y-%m-%d).txt" -{ - echo "Date of analysis: $(date)" - echo "Log file: $log_file" - echo "Total lines processed: $total_lines" - echo "Total error count: $error_count" - echo -e "\nTop 5 error messages:" - echo "$sorted_error_messages" - echo -e "\nCritical events with line numbers:" - for event in "${critical_events[@]}"; do - echo "$event" - done -} > "$summary_report" - -echo "Summary report generated: $summary_report" - diff --git a/Challenges/Day_5/logfile.sh b/Challenges/Day_5/logfile.sh new file mode 100644 index 0000000..1058333 --- /dev/null +++ b/Challenges/Day_5/logfile.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# Usage: ./log_generator.sh + +if [ "$#" -ne 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +log_file_path="$1" +num_lines="$2" + +if [ -e "$log_file_path" ]; then + echo "Error: File already exists at $log_file_path." + exit 1 +fi + +# List of possible log message levels +log_levels=("INFO" "DEBUG" "ERROR" "WARNING" "CRITICAL") + +# List of possible error messages +error_messages=("Failed to connect" "Disk full" "Segmentation fault" "Invalid input" "Out of memory") + +# Function to generate a random log line +generate_log_line() { + local log_level="${log_levels[$((RANDOM % ${#log_levels[@]}))]}" + local error_msg="" + if [ "$log_level" == "ERROR" ]; then + error_msg="${error_messages[$((RANDOM % ${#error_messages[@]}))]}" + fi + echo "$(date '+%Y-%m-%d %H:%M:%S') [$log_level] $error_msg - $RANDOM" +} + +# Create the log file with random log lines +touch "$log_file_path" +for ((i=0; i> "$log_file_path" +done + +echo "Log file created at: $log_file_path with $num_lines lines." diff --git a/Challenges/Day_5/logs_archive/2023-08-04_20-56-29_log.txt b/Challenges/Day_5/logs_archive/2023-08-04_20-56-29_log.txt new file mode 100644 index 0000000..8427854 --- /dev/null +++ b/Challenges/Day_5/logs_archive/2023-08-04_20-56-29_log.txt @@ -0,0 +1,10 @@ +2023-08-04 20:56:28 [WARNING] - 22568 +2023-08-04 20:56:28 [INFO] - 30298 +2023-08-04 20:56:28 [WARNING] - 9298 +2023-08-04 20:56:28 [DEBUG] - 3423 +2023-08-04 20:56:28 [ERROR] Segmentation fault - 24603 +2023-08-04 20:56:28 [WARNING] - 27058 +2023-08-04 20:56:28 [DEBUG] - 18326 +2023-08-04 20:56:28 [CRITICAL] - 31723 +2023-08-04 20:56:28 [CRITICAL] - 13117 +2023-08-04 20:56:28 [ERROR] Invalid input - 28171 diff --git a/Challenges/Day_5/logs_archive/2023-08-04_20-57-44_log.txt b/Challenges/Day_5/logs_archive/2023-08-04_20-57-44_log.txt new file mode 100644 index 0000000..0b1fd30 --- /dev/null +++ b/Challenges/Day_5/logs_archive/2023-08-04_20-57-44_log.txt @@ -0,0 +1,10 @@ +2023-08-04 20:57:40 [WARNING] - 1914 +2023-08-04 20:57:40 [DEBUG] - 17730 +2023-08-04 20:57:40 [DEBUG] - 11473 +2023-08-04 20:57:40 [DEBUG] - 14981 +2023-08-04 20:57:40 [INFO] - 9504 +2023-08-04 20:57:40 [CRITICAL] - 19334 +2023-08-04 20:57:40 [CRITICAL] - 27551 +2023-08-04 20:57:40 [ERROR] Failed to connect - 12789 +2023-08-04 20:57:40 [DEBUG] - 22288 +2023-08-04 20:57:40 [WARNING] - 22774 diff --git a/Challenges/Day_5/logs_archive/2023-08-04_21-02-04_log.txt b/Challenges/Day_5/logs_archive/2023-08-04_21-02-04_log.txt new file mode 100644 index 0000000..34d5a93 --- /dev/null +++ b/Challenges/Day_5/logs_archive/2023-08-04_21-02-04_log.txt @@ -0,0 +1,100 @@ +2023-08-04 21:01:50 [WARNING] - 504 +2023-08-04 21:01:50 [WARNING] - 25715 +2023-08-04 21:01:50 [WARNING] - 29291 +2023-08-04 21:01:50 [INFO] - 29919 +2023-08-04 21:01:50 [DEBUG] - 16335 +2023-08-04 21:01:50 [DEBUG] - 8430 +2023-08-04 21:01:50 [CRITICAL] - 1766 +2023-08-04 21:01:50 [WARNING] - 22808 +2023-08-04 21:01:50 [ERROR] Disk full - 1102 +2023-08-04 21:01:50 [INFO] - 24819 +2023-08-04 21:01:50 [CRITICAL] - 11674 +2023-08-04 21:01:50 [WARNING] - 31474 +2023-08-04 21:01:50 [CRITICAL] - 23117 +2023-08-04 21:01:50 [WARNING] - 26618 +2023-08-04 21:01:50 [WARNING] - 27961 +2023-08-04 21:01:50 [CRITICAL] - 15256 +2023-08-04 21:01:50 [INFO] - 18327 +2023-08-04 21:01:50 [WARNING] - 32420 +2023-08-04 21:01:50 [WARNING] - 11757 +2023-08-04 21:01:50 [INFO] - 29949 +2023-08-04 21:01:50 [DEBUG] - 26742 +2023-08-04 21:01:50 [DEBUG] - 22638 +2023-08-04 21:01:50 [ERROR] Segmentation fault - 13400 +2023-08-04 21:01:50 [CRITICAL] - 27423 +2023-08-04 21:01:50 [WARNING] - 10263 +2023-08-04 21:01:50 [WARNING] - 30682 +2023-08-04 21:01:50 [CRITICAL] - 21693 +2023-08-04 21:01:50 [DEBUG] - 8618 +2023-08-04 21:01:50 [DEBUG] - 11482 +2023-08-04 21:01:50 [DEBUG] - 22261 +2023-08-04 21:01:50 [DEBUG] - 12909 +2023-08-04 21:01:50 [INFO] - 20217 +2023-08-04 21:01:50 [INFO] - 25206 +2023-08-04 21:01:50 [ERROR] Invalid input - 27981 +2023-08-04 21:01:50 [WARNING] - 16941 +2023-08-04 21:01:50 [CRITICAL] - 7130 +2023-08-04 21:01:50 [DEBUG] - 10697 +2023-08-04 21:01:50 [DEBUG] - 5065 +2023-08-04 21:01:50 [ERROR] Invalid input - 2234 +2023-08-04 21:01:50 [CRITICAL] - 3756 +2023-08-04 21:01:50 [ERROR] Failed to connect - 851 +2023-08-04 21:01:50 [INFO] - 26301 +2023-08-04 21:01:50 [ERROR] Disk full - 1932 +2023-08-04 21:01:50 [ERROR] Disk full - 8283 +2023-08-04 21:01:50 [ERROR] Invalid input - 29952 +2023-08-04 21:01:50 [INFO] - 24164 +2023-08-04 21:01:50 [WARNING] - 30933 +2023-08-04 21:01:50 [CRITICAL] - 11533 +2023-08-04 21:01:50 [ERROR] Out of memory - 31006 +2023-08-04 21:01:50 [WARNING] - 27872 +2023-08-04 21:01:50 [WARNING] - 1534 +2023-08-04 21:01:50 [INFO] - 25032 +2023-08-04 21:01:50 [WARNING] - 10737 +2023-08-04 21:01:50 [INFO] - 12709 +2023-08-04 21:01:50 [WARNING] - 16921 +2023-08-04 21:01:50 [CRITICAL] - 4344 +2023-08-04 21:01:50 [DEBUG] - 26082 +2023-08-04 21:01:50 [DEBUG] - 6613 +2023-08-04 21:01:50 [ERROR] Failed to connect - 17706 +2023-08-04 21:01:50 [ERROR] Invalid input - 30473 +2023-08-04 21:01:50 [ERROR] Segmentation fault - 31538 +2023-08-04 21:01:50 [INFO] - 19637 +2023-08-04 21:01:50 [INFO] - 15479 +2023-08-04 21:01:50 [CRITICAL] - 9403 +2023-08-04 21:01:50 [WARNING] - 28486 +2023-08-04 21:01:50 [ERROR] Failed to connect - 17157 +2023-08-04 21:01:50 [DEBUG] - 98 +2023-08-04 21:01:50 [DEBUG] - 31381 +2023-08-04 21:01:50 [ERROR] Invalid input - 8298 +2023-08-04 21:01:50 [ERROR] Disk full - 15633 +2023-08-04 21:01:50 [DEBUG] - 26229 +2023-08-04 21:01:50 [CRITICAL] - 4871 +2023-08-04 21:01:50 [ERROR] Segmentation fault - 6570 +2023-08-04 21:01:50 [DEBUG] - 24821 +2023-08-04 21:01:50 [WARNING] - 20163 +2023-08-04 21:01:50 [CRITICAL] - 28076 +2023-08-04 21:01:50 [INFO] - 27421 +2023-08-04 21:01:50 [INFO] - 16160 +2023-08-04 21:01:50 [ERROR] Invalid input - 17594 +2023-08-04 21:01:50 [INFO] - 8450 +2023-08-04 21:01:50 [WARNING] - 18112 +2023-08-04 21:01:50 [WARNING] - 6560 +2023-08-04 21:01:50 [WARNING] - 12961 +2023-08-04 21:01:50 [CRITICAL] - 26040 +2023-08-04 21:01:50 [DEBUG] - 29861 +2023-08-04 21:01:50 [WARNING] - 30179 +2023-08-04 21:01:50 [INFO] - 16476 +2023-08-04 21:01:50 [CRITICAL] - 28114 +2023-08-04 21:01:51 [WARNING] - 17459 +2023-08-04 21:01:51 [WARNING] - 12335 +2023-08-04 21:01:51 [DEBUG] - 25748 +2023-08-04 21:01:51 [WARNING] - 5690 +2023-08-04 21:01:51 [DEBUG] - 30108 +2023-08-04 21:01:51 [ERROR] Invalid input - 4207 +2023-08-04 21:01:51 [ERROR] Failed to connect - 26147 +2023-08-04 21:01:51 [WARNING] - 4941 +2023-08-04 21:01:51 [ERROR] Failed to connect - 10106 +2023-08-04 21:01:51 [DEBUG] - 26276 +2023-08-04 21:01:51 [DEBUG] - 17358 +2023-08-04 21:01:51 [ERROR] Failed to connect - 26776 diff --git a/Challenges/Day_5/logs_archive/2023-08-04_21-09-31_log.txt b/Challenges/Day_5/logs_archive/2023-08-04_21-09-31_log.txt new file mode 100644 index 0000000..edc7416 --- /dev/null +++ b/Challenges/Day_5/logs_archive/2023-08-04_21-09-31_log.txt @@ -0,0 +1,100 @@ +2023-08-04 21:09:26 [ERROR] Segmentation fault - 24312 +2023-08-04 21:09:26 [CRITICAL] - 2684 +2023-08-04 21:09:26 [DEBUG] - 21547 +2023-08-04 21:09:26 [ERROR] Invalid input - 31998 +2023-08-04 21:09:26 [CRITICAL] - 9186 +2023-08-04 21:09:26 [WARNING] - 16011 +2023-08-04 21:09:26 [CRITICAL] - 20235 +2023-08-04 21:09:26 [CRITICAL] - 7941 +2023-08-04 21:09:26 [INFO] - 6671 +2023-08-04 21:09:26 [INFO] - 9989 +2023-08-04 21:09:26 [WARNING] - 11146 +2023-08-04 21:09:26 [INFO] - 6323 +2023-08-04 21:09:26 [DEBUG] - 31706 +2023-08-04 21:09:26 [INFO] - 21034 +2023-08-04 21:09:26 [WARNING] - 20281 +2023-08-04 21:09:26 [INFO] - 31355 +2023-08-04 21:09:26 [CRITICAL] - 4878 +2023-08-04 21:09:26 [WARNING] - 4841 +2023-08-04 21:09:26 [WARNING] - 27793 +2023-08-04 21:09:26 [DEBUG] - 27489 +2023-08-04 21:09:26 [DEBUG] - 14327 +2023-08-04 21:09:26 [WARNING] - 8993 +2023-08-04 21:09:26 [INFO] - 17163 +2023-08-04 21:09:26 [DEBUG] - 20832 +2023-08-04 21:09:26 [DEBUG] - 12960 +2023-08-04 21:09:26 [ERROR] Disk full - 15336 +2023-08-04 21:09:26 [CRITICAL] - 20773 +2023-08-04 21:09:26 [DEBUG] - 12756 +2023-08-04 21:09:26 [CRITICAL] - 31065 +2023-08-04 21:09:26 [INFO] - 7861 +2023-08-04 21:09:26 [CRITICAL] - 12705 +2023-08-04 21:09:26 [CRITICAL] - 10988 +2023-08-04 21:09:26 [WARNING] - 10263 +2023-08-04 21:09:26 [DEBUG] - 8854 +2023-08-04 21:09:26 [WARNING] - 5694 +2023-08-04 21:09:26 [WARNING] - 27476 +2023-08-04 21:09:26 [ERROR] Disk full - 15310 +2023-08-04 21:09:26 [ERROR] Failed to connect - 1304 +2023-08-04 21:09:26 [ERROR] Invalid input - 1229 +2023-08-04 21:09:26 [ERROR] Failed to connect - 27254 +2023-08-04 21:09:26 [ERROR] Failed to connect - 24432 +2023-08-04 21:09:26 [CRITICAL] - 28905 +2023-08-04 21:09:26 [WARNING] - 19589 +2023-08-04 21:09:26 [INFO] - 4914 +2023-08-04 21:09:26 [WARNING] - 13364 +2023-08-04 21:09:26 [WARNING] - 5592 +2023-08-04 21:09:26 [INFO] - 16753 +2023-08-04 21:09:26 [CRITICAL] - 13018 +2023-08-04 21:09:26 [CRITICAL] - 14029 +2023-08-04 21:09:26 [CRITICAL] - 10729 +2023-08-04 21:09:26 [INFO] - 5593 +2023-08-04 21:09:26 [CRITICAL] - 2713 +2023-08-04 21:09:26 [ERROR] Invalid input - 1911 +2023-08-04 21:09:26 [ERROR] Segmentation fault - 9646 +2023-08-04 21:09:26 [DEBUG] - 8963 +2023-08-04 21:09:26 [CRITICAL] - 11022 +2023-08-04 21:09:26 [DEBUG] - 10505 +2023-08-04 21:09:26 [INFO] - 24539 +2023-08-04 21:09:26 [WARNING] - 6796 +2023-08-04 21:09:26 [ERROR] Disk full - 8374 +2023-08-04 21:09:26 [CRITICAL] - 20009 +2023-08-04 21:09:26 [ERROR] Segmentation fault - 8354 +2023-08-04 21:09:26 [CRITICAL] - 30747 +2023-08-04 21:09:26 [INFO] - 7317 +2023-08-04 21:09:26 [WARNING] - 14046 +2023-08-04 21:09:26 [WARNING] - 21394 +2023-08-04 21:09:26 [ERROR] Segmentation fault - 16251 +2023-08-04 21:09:26 [WARNING] - 3419 +2023-08-04 21:09:26 [DEBUG] - 6592 +2023-08-04 21:09:26 [WARNING] - 22008 +2023-08-04 21:09:26 [WARNING] - 14022 +2023-08-04 21:09:26 [WARNING] - 12739 +2023-08-04 21:09:26 [WARNING] - 6306 +2023-08-04 21:09:26 [WARNING] - 18460 +2023-08-04 21:09:26 [WARNING] - 2358 +2023-08-04 21:09:26 [CRITICAL] - 14662 +2023-08-04 21:09:26 [WARNING] - 31554 +2023-08-04 21:09:26 [ERROR] Out of memory - 26636 +2023-08-04 21:09:26 [INFO] - 30236 +2023-08-04 21:09:26 [CRITICAL] - 3496 +2023-08-04 21:09:26 [INFO] - 30667 +2023-08-04 21:09:26 [INFO] - 12262 +2023-08-04 21:09:26 [CRITICAL] - 5372 +2023-08-04 21:09:26 [WARNING] - 5747 +2023-08-04 21:09:26 [DEBUG] - 19048 +2023-08-04 21:09:26 [CRITICAL] - 26406 +2023-08-04 21:09:26 [INFO] - 1324 +2023-08-04 21:09:26 [INFO] - 31661 +2023-08-04 21:09:26 [WARNING] - 265 +2023-08-04 21:09:26 [DEBUG] - 5259 +2023-08-04 21:09:26 [DEBUG] - 23858 +2023-08-04 21:09:26 [ERROR] Failed to connect - 19322 +2023-08-04 21:09:26 [INFO] - 16898 +2023-08-04 21:09:26 [ERROR] Out of memory - 16921 +2023-08-04 21:09:26 [CRITICAL] - 12392 +2023-08-04 21:09:26 [WARNING] - 13809 +2023-08-04 21:09:26 [CRITICAL] - 30022 +2023-08-04 21:09:26 [CRITICAL] - 22011 +2023-08-04 21:09:26 [INFO] - 16574 +2023-08-04 21:09:26 [DEBUG] - 26568 diff --git a/Challenges/Day_5/logs_archive/2023-08-04_21-09-57_log.txt b/Challenges/Day_5/logs_archive/2023-08-04_21-09-57_log.txt new file mode 100644 index 0000000..b7ef48f --- /dev/null +++ b/Challenges/Day_5/logs_archive/2023-08-04_21-09-57_log.txt @@ -0,0 +1,100 @@ +2023-08-04 21:09:55 [CRITICAL] - 3929 +2023-08-04 21:09:55 [DEBUG] - 22801 +2023-08-04 21:09:55 [ERROR] Failed to connect - 13076 +2023-08-04 21:09:55 [CRITICAL] - 27632 +2023-08-04 21:09:55 [WARNING] - 29340 +2023-08-04 21:09:55 [CRITICAL] - 4346 +2023-08-04 21:09:55 [INFO] - 16754 +2023-08-04 21:09:55 [ERROR] Out of memory - 10133 +2023-08-04 21:09:55 [INFO] - 764 +2023-08-04 21:09:55 [INFO] - 13938 +2023-08-04 21:09:55 [WARNING] - 11163 +2023-08-04 21:09:55 [DEBUG] - 19492 +2023-08-04 21:09:55 [CRITICAL] - 3052 +2023-08-04 21:09:55 [INFO] - 17289 +2023-08-04 21:09:55 [ERROR] Failed to connect - 9903 +2023-08-04 21:09:55 [ERROR] Segmentation fault - 27943 +2023-08-04 21:09:55 [WARNING] - 15238 +2023-08-04 21:09:55 [ERROR] Segmentation fault - 7222 +2023-08-04 21:09:55 [ERROR] Segmentation fault - 13139 +2023-08-04 21:09:55 [CRITICAL] - 11473 +2023-08-04 21:09:55 [ERROR] Invalid input - 10336 +2023-08-04 21:09:55 [CRITICAL] - 7348 +2023-08-04 21:09:55 [WARNING] - 13411 +2023-08-04 21:09:55 [WARNING] - 24036 +2023-08-04 21:09:55 [DEBUG] - 25244 +2023-08-04 21:09:55 [WARNING] - 18987 +2023-08-04 21:09:55 [ERROR] Invalid input - 25139 +2023-08-04 21:09:55 [INFO] - 12460 +2023-08-04 21:09:55 [CRITICAL] - 21130 +2023-08-04 21:09:55 [ERROR] Out of memory - 1634 +2023-08-04 21:09:55 [CRITICAL] - 32067 +2023-08-04 21:09:55 [ERROR] Failed to connect - 5123 +2023-08-04 21:09:55 [INFO] - 20454 +2023-08-04 21:09:55 [WARNING] - 19307 +2023-08-04 21:09:55 [DEBUG] - 10969 +2023-08-04 21:09:55 [ERROR] Invalid input - 16559 +2023-08-04 21:09:55 [ERROR] Disk full - 18145 +2023-08-04 21:09:55 [CRITICAL] - 26192 +2023-08-04 21:09:55 [CRITICAL] - 4691 +2023-08-04 21:09:55 [CRITICAL] - 5726 +2023-08-04 21:09:55 [CRITICAL] - 14499 +2023-08-04 21:09:55 [INFO] - 7286 +2023-08-04 21:09:55 [WARNING] - 13800 +2023-08-04 21:09:55 [ERROR] Failed to connect - 3615 +2023-08-04 21:09:55 [CRITICAL] - 23122 +2023-08-04 21:09:55 [CRITICAL] - 28771 +2023-08-04 21:09:55 [WARNING] - 14240 +2023-08-04 21:09:55 [CRITICAL] - 7026 +2023-08-04 21:09:55 [CRITICAL] - 829 +2023-08-04 21:09:55 [ERROR] Disk full - 18186 +2023-08-04 21:09:55 [DEBUG] - 31581 +2023-08-04 21:09:55 [DEBUG] - 27662 +2023-08-04 21:09:55 [CRITICAL] - 18492 +2023-08-04 21:09:55 [DEBUG] - 22751 +2023-08-04 21:09:55 [CRITICAL] - 12559 +2023-08-04 21:09:55 [CRITICAL] - 31784 +2023-08-04 21:09:55 [ERROR] Invalid input - 22952 +2023-08-04 21:09:55 [DEBUG] - 26618 +2023-08-04 21:09:55 [WARNING] - 4952 +2023-08-04 21:09:55 [CRITICAL] - 20400 +2023-08-04 21:09:55 [INFO] - 15179 +2023-08-04 21:09:55 [CRITICAL] - 29841 +2023-08-04 21:09:55 [WARNING] - 15758 +2023-08-04 21:09:55 [CRITICAL] - 1329 +2023-08-04 21:09:55 [CRITICAL] - 20636 +2023-08-04 21:09:55 [CRITICAL] - 25357 +2023-08-04 21:09:55 [WARNING] - 3347 +2023-08-04 21:09:55 [CRITICAL] - 6565 +2023-08-04 21:09:55 [CRITICAL] - 7359 +2023-08-04 21:09:55 [DEBUG] - 24961 +2023-08-04 21:09:55 [INFO] - 11956 +2023-08-04 21:09:55 [DEBUG] - 30545 +2023-08-04 21:09:55 [CRITICAL] - 18689 +2023-08-04 21:09:55 [CRITICAL] - 3470 +2023-08-04 21:09:55 [INFO] - 29815 +2023-08-04 21:09:55 [ERROR] Out of memory - 20648 +2023-08-04 21:09:55 [INFO] - 24715 +2023-08-04 21:09:55 [WARNING] - 4905 +2023-08-04 21:09:55 [ERROR] Failed to connect - 31139 +2023-08-04 21:09:55 [ERROR] Out of memory - 29783 +2023-08-04 21:09:55 [INFO] - 15814 +2023-08-04 21:09:55 [INFO] - 15266 +2023-08-04 21:09:55 [CRITICAL] - 15655 +2023-08-04 21:09:55 [WARNING] - 32228 +2023-08-04 21:09:55 [CRITICAL] - 8297 +2023-08-04 21:09:55 [CRITICAL] - 21109 +2023-08-04 21:09:55 [CRITICAL] - 22747 +2023-08-04 21:09:55 [DEBUG] - 12621 +2023-08-04 21:09:55 [INFO] - 3760 +2023-08-04 21:09:55 [INFO] - 25159 +2023-08-04 21:09:55 [CRITICAL] - 6292 +2023-08-04 21:09:55 [INFO] - 12233 +2023-08-04 21:09:55 [ERROR] Out of memory - 4775 +2023-08-04 21:09:55 [DEBUG] - 26887 +2023-08-04 21:09:55 [INFO] - 20624 +2023-08-04 21:09:55 [WARNING] - 22899 +2023-08-04 21:09:55 [ERROR] Failed to connect - 29599 +2023-08-04 21:09:55 [DEBUG] - 12017 +2023-08-04 21:09:55 [ERROR] Failed to connect - 9361 +2023-08-04 21:09:55 [CRITICAL] - 10707 diff --git a/Challenges/Day_5/report.txt b/Challenges/Day_5/report.txt new file mode 100644 index 0000000..e2b743b --- /dev/null +++ b/Challenges/Day_5/report.txt @@ -0,0 +1,45 @@ +Date of analysis: 2023-08-04_21-09-57 +Log file name: logs.txt +Total lines processed: 100 +Total error count: 21 +Top 5 error messages with their occurrence count: + 7 Failed to connect + 5 Out of memory + 4 Invalid input + 3 Segmentation fault + 2 Disk full +List of critical events with line numbers: +Line No. 1 : 2023-08-04 21:09:55 [CRITICAL] - 3929 +Line No. 4 : 2023-08-04 21:09:55 [CRITICAL] - 27632 +Line No. 6 : 2023-08-04 21:09:55 [CRITICAL] - 4346 +Line No. 13 : 2023-08-04 21:09:55 [CRITICAL] - 3052 +Line No. 20 : 2023-08-04 21:09:55 [CRITICAL] - 11473 +Line No. 22 : 2023-08-04 21:09:55 [CRITICAL] - 7348 +Line No. 29 : 2023-08-04 21:09:55 [CRITICAL] - 21130 +Line No. 31 : 2023-08-04 21:09:55 [CRITICAL] - 32067 +Line No. 38 : 2023-08-04 21:09:55 [CRITICAL] - 26192 +Line No. 39 : 2023-08-04 21:09:55 [CRITICAL] - 4691 +Line No. 40 : 2023-08-04 21:09:55 [CRITICAL] - 5726 +Line No. 41 : 2023-08-04 21:09:55 [CRITICAL] - 14499 +Line No. 45 : 2023-08-04 21:09:55 [CRITICAL] - 23122 +Line No. 46 : 2023-08-04 21:09:55 [CRITICAL] - 28771 +Line No. 48 : 2023-08-04 21:09:55 [CRITICAL] - 7026 +Line No. 49 : 2023-08-04 21:09:55 [CRITICAL] - 829 +Line No. 53 : 2023-08-04 21:09:55 [CRITICAL] - 18492 +Line No. 55 : 2023-08-04 21:09:55 [CRITICAL] - 12559 +Line No. 56 : 2023-08-04 21:09:55 [CRITICAL] - 31784 +Line No. 60 : 2023-08-04 21:09:55 [CRITICAL] - 20400 +Line No. 62 : 2023-08-04 21:09:55 [CRITICAL] - 29841 +Line No. 64 : 2023-08-04 21:09:55 [CRITICAL] - 1329 +Line No. 65 : 2023-08-04 21:09:55 [CRITICAL] - 20636 +Line No. 66 : 2023-08-04 21:09:55 [CRITICAL] - 25357 +Line No. 68 : 2023-08-04 21:09:55 [CRITICAL] - 6565 +Line No. 69 : 2023-08-04 21:09:55 [CRITICAL] - 7359 +Line No. 73 : 2023-08-04 21:09:55 [CRITICAL] - 18689 +Line No. 74 : 2023-08-04 21:09:55 [CRITICAL] - 3470 +Line No. 83 : 2023-08-04 21:09:55 [CRITICAL] - 15655 +Line No. 85 : 2023-08-04 21:09:55 [CRITICAL] - 8297 +Line No. 86 : 2023-08-04 21:09:55 [CRITICAL] - 21109 +Line No. 87 : 2023-08-04 21:09:55 [CRITICAL] - 22747 +Line No. 91 : 2023-08-04 21:09:55 [CRITICAL] - 6292 +Line No. 100 : 2023-08-04 21:09:55 [CRITICAL] - 10707 diff --git a/Challenges/Day_6/broken_myst/brokenday.md b/Challenges/Day_6/broken_myst/brokenday.md index c24db86..2d5a7c1 100644 --- a/Challenges/Day_6/broken_myst/brokenday.md +++ b/Challenges/Day_6/broken_myst/brokenday.md @@ -1,74 +1,74 @@ -# Day 6 Bash Scripting Challenge: The Mysterious Script - -## Introduction - -Welcome to Day 6 of the 7-day Bash scripting challenge! In this challenge, you will encounter a mysterious Bash script named `mystery.sh`. The script lacks documentation and comments, leaving its purpose and functionality shrouded in mystery. Your mission is to unravel the secrets of this script, understand its objective, and improve it by adding comments and explanations. - -## Challenge Overview - -- [Explore the Script](#explore-the-script) -- [Run the Script](#run-the-script) -- [Debugging and Decoding](#debugging-and-decoding) -- [Identify the Objective](#identify-the-objective) -- [Add Comments and Explanation](#add-comments-and-explanation) -- [Optimize (Optional)](#optimize-optional) -- [Present Your Findings](#present-your-findings) - -## Getting Started - -1. Fork this repository to your GitHub account. -2. Clone the forked repository to your local machine. -3. Inside the repository, you will find `mystery.sh`. This is the script you need to analyze and improve. - -## Challenge Steps - -### Explore the Script - -Begin by examining the contents of `mystery.sh`. The script contains various Bash commands, functions, or variables without any comments or explanations. Make note of any patterns or interesting code segments that might give you hints about the script's purpose. - -### Run the Script - -Execute `mystery.sh` using the command `bash mystery.sh` and observe its behavior. Pay attention to any output or changes in the system that might occur during the script's execution. - -### Debugging and Decoding - -Identify and fix any potential errors or bugs in the script that may prevent it from running correctly. Analyze the logic of the script to understand how it processes data or performs operations. - -### Identify the Objective - -Based on your observations and analysis, determine the main objective of the script. What is it trying to accomplish? Try to reverse-engineer the script's logic to understand its intended purpose. - -### Add Comments and Explanation - -Now that you have a good understanding of the script's purpose, modify `mystery.sh` to add clear and concise comments at crucial points in the code. Explain the logic behind each major operation and any critical decisions made during the script's execution. - -### Optimize (Optional) - -If you think there are opportunities to optimize the script's performance or make it more efficient, you can implement those changes. However, this step is entirely optional. - -### Present Your Findings - -Document your journey of unraveling the mysterious script, explaining the steps you took to understand it and any challenges you encountered. Showcase the modified `mystery.sh` script with added comments and explanations. - -## How to Participate - -1. Work on the challenge on your local machine, making necessary improvements to `mystery.sh`. -2. Commit your changes and push them to your forked repository on GitHub. -3. Create a pull request from your forked repository to the original challenge repository. -4. In the pull request description, share your findings, explanations, and any insights you gained from completing the challenge. - -## Tips and Guidelines - -- Use common Bash debugging techniques such as `echo` statements, `set -x`, or `set -e` to help you understand the script's flow. -- Pay attention to variable names, as they might give you clues about the script's purpose. -- Remember that the script may contain red herrings or distractions to make the challenge more interesting. - -### Hint^ - -During this challenge, I would use internet resources responsibly. I might search for information on Bash commands, encryption techniques (e.g., ROT13), or debugging tips that could help me understand and unravel the script's complexity. - -## Have Fun and Happy Scripting! - -Approach this challenge with curiosity and a detective mindset. Enjoy the process of decoding "The Mysterious Script" and uncovering its secrets! If you have any questions or need assistance, feel free to open an issue in this repository. - -Good luck, and may the scripts be with you! +# Day 6 Bash Scripting Challenge: The Mysterious Script + +## Introduction + +Welcome to Day 6 of the 7-day Bash scripting challenge! In this challenge, you will encounter a mysterious Bash script named `mystery.sh`. The script lacks documentation and comments, leaving its purpose and functionality shrouded in mystery. Your mission is to unravel the secrets of this script, understand its objective, and improve it by adding comments and explanations. + +## Challenge Overview + +- [Explore the Script](#explore-the-script) +- [Run the Script](#run-the-script) +- [Debugging and Decoding](#debugging-and-decoding) +- [Identify the Objective](#identify-the-objective) +- [Add Comments and Explanation](#add-comments-and-explanation) +- [Optimize (Optional)](#optimize-optional) +- [Present Your Findings](#present-your-findings) + +## Getting Started + +1. Fork this repository to your GitHub account. +2. Clone the forked repository to your local machine. +3. Inside the repository, you will find `mystery.sh`. This is the script you need to analyze and improve. + +## Challenge Steps + +### Explore the Script + +Begin by examining the contents of `mystery.sh`. The script contains various Bash commands, functions, or variables without any comments or explanations. Make note of any patterns or interesting code segments that might give you hints about the script's purpose. + +### Run the Script + +Execute `mystery.sh` using the command `bash mystery.sh` and observe its behavior. Pay attention to any output or changes in the system that might occur during the script's execution. + +### Debugging and Decoding + +Identify and fix any potential errors or bugs in the script that may prevent it from running correctly. Analyze the logic of the script to understand how it processes data or performs operations. + +### Identify the Objective + +Based on your observations and analysis, determine the main objective of the script. What is it trying to accomplish? Try to reverse-engineer the script's logic to understand its intended purpose. + +### Add Comments and Explanation + +Now that you have a good understanding of the script's purpose, modify `mystery.sh` to add clear and concise comments at crucial points in the code. Explain the logic behind each major operation and any critical decisions made during the script's execution. + +### Optimize (Optional) + +If you think there are opportunities to optimize the script's performance or make it more efficient, you can implement those changes. However, this step is entirely optional. + +### Present Your Findings + +Document your journey of unraveling the mysterious script, explaining the steps you took to understand it and any challenges you encountered. Showcase the modified `mystery.sh` script with added comments and explanations. + +## How to Participate + +1. Work on the challenge on your local machine, making necessary improvements to `mystery.sh`. +2. Commit your changes and push them to your forked repository on GitHub. +3. Create a pull request from your forked repository to the original challenge repository. +4. In the pull request description, share your findings, explanations, and any insights you gained from completing the challenge. + +## Tips and Guidelines + +- Use common Bash debugging techniques such as `echo` statements, `set -x`, or `set -e` to help you understand the script's flow. +- Pay attention to variable names, as they might give you clues about the script's purpose. +- Remember that the script may contain red herrings or distractions to make the challenge more interesting. + +### Hint^ + +During this challenge, I would use internet resources responsibly. I might search for information on Bash commands, encryption techniques (e.g., ROT13), or debugging tips that could help me understand and unravel the script's complexity. + +## Have Fun and Happy Scripting! + +Approach this challenge with curiosity and a detective mindset. Enjoy the process of decoding "The Mysterious Script" and uncovering its secrets! If you have any questions or need assistance, feel free to open an issue in this repository. + +Good luck, and may the scripts be with you! diff --git a/Challenges/Day_6/broken_myst/mystery.sh b/Challenges/Day_6/broken_myst/mystery.sh index dba59f3..09118f9 100644 --- a/Challenges/Day_6/broken_myst/mystery.sh +++ b/Challenges/Day_6/broken_myst/mystery.sh @@ -1,35 +1,30 @@ #!/bin/bash -# Welcome to the Mysterious Script Challenge! -# Your task is to unravel the mystery behind this script and understand what it does. -# Once you've deciphered its objective, your mission is to improve the script by adding comments and explanations for clarity. - -# DISCLAIMER: This script is purely fictional and does not perform any harmful actions. -# It's designed to challenge your scripting skills and creativity. - # The Mysterious Function mysterious_function() { + #make a input file and write a sentence in it local input_file="$1" + #make a output file local output_file="$2" - # + # replacing a-l alphabets with n-z and vice versa tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" - # + # reverse the order of the sentence rev "$output_file" > "reversed_temp.txt" - # + # assign any random number between 1 to 10 random_number=$(( ( RANDOM % 10 ) + 1 )) # Mystery loop: for (( i=0; i<$random_number; i++ )); do - # + # reverse the order of the sentence and save it in temp_rev.txt rev "reversed_temp.txt" > "temp_rev.txt" - # + # replacing a-l alphabets with n-z and vice versa from temp_rev.txt and saving to temp_enc.txt tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp_rev.txt" > "temp_enc.txt" - # + # renaming the file temp_enc.txt to reversed_temp.txt mv "temp_enc.txt" "reversed_temp.txt" done @@ -37,20 +32,17 @@ mysterious_function() { rm "temp_rev.txt" # The mystery continues... - # The script will continue with more operations that you need to figure out! + rev "reversed_temp.txt" > "$output_file" + rm "reversed_temp.txt" } # Main Script Execution - # Check if two arguments are provided if [ $# -ne 2 ]; then echo "Usage: $0 " exit 1 fi -input_file="$1" -output_file="$2" - # Check if the input file exists if [ ! -f "$input_file" ]; then echo "Error: Input file not found!" @@ -59,6 +51,5 @@ fi # Call the mysterious function to begin the process mysterious_function "$input_file" "$output_file" - # Display the mysterious output echo "The mysterious process is complete. Check the '$output_file' for the result!" diff --git a/Challenges/Day_6/broken_myst/new.txt b/Challenges/Day_6/broken_myst/new.txt new file mode 100644 index 0000000..7eeef8a --- /dev/null +++ b/Challenges/Day_6/broken_myst/new.txt @@ -0,0 +1 @@ +hello, this is shivani \ No newline at end of file diff --git a/Challenges/Day_6/broken_resto/menu.txt b/Challenges/Day_6/broken_resto/menu.txt index bab3925..6e3de27 100644 --- a/Challenges/Day_6/broken_resto/menu.txt +++ b/Challenges/Day_6/broken_resto/menu.txt @@ -1,9 +1,9 @@ -Burger, 120 -Pizza, 250 -Salad, 180 -Soda, 40 -Pasta, 180 -Sandwich, 150 -Coke, 50 -Fries, 100 -Ice Cream, 120 +Burger, 120 +Pizza, 250 +Salad, 180 +Soda, 40 +Pasta, 180 +Sandwich, 150 +Coke, 50 +Fries, 100 +Ice Cream, 120 diff --git a/Challenges/Day_6/broken_resto/readmeFirst.md b/Challenges/Day_6/broken_resto/readmeFirst.md index 88d7178..87c9f59 100644 --- a/Challenges/Day_6/broken_resto/readmeFirst.md +++ b/Challenges/Day_6/broken_resto/readmeFirst.md @@ -1,47 +1,47 @@ -## . - -# The Hungry Bash - Restaurant Order System Challenge - -Welcome to "The Hungry Bash" challenge! 🍔🍕🥗🥤 - -## Challenge Description - -In this challenge, you will be working on a Bash-based restaurant order system. The provided script, `restaurant_order.sh`, is partially broken and missing some crucial parts. Your task is to fix and complete the script to create a fully functional restaurant order system. - -### The Broken Script - -The `restaurant_order.sh` script is provided to you, but some essential parts are missing or not functioning correctly. Here are the broken parts: - -1. **Missing Menu Display**: The script is missing the code to read and display the menu from the `menu.txt` file. You need to implement the function to read the menu and display it to the customers. - -2. **Invalid User Input Handling**: The script is not handling invalid user input, such as entering a non-existent item number or negative quantities. You need to implement error handling to prompt users for valid inputs when necessary. - -3. **Total Bill Calculation**: The script is not calculating the correct total bill based on the customer's order. You need to implement the function to calculate the total bill accurately. - -### Your Task - -Your mission is to complete the `restaurant_order.sh` script and make it fully functional. Once you fix all the broken parts, the script should provide a smooth dining experience for our customers. - -## Getting Started - -1. Fork this repository to your GitHub account. - -2. Clone the forked repository to your local machine. - -3. Open the `menu.txt` file and verify that it contains a list of available food items, each on a separate line, with their corresponding prices in rupees, separated by a comma. - -4. Open the `restaurant_order.sh` script and begin your coding journey to fix the broken parts. - -## Submission - -Once you complete the script, commit your changes, and push them to your forked repository. Finally, submit a pull request to the original repository to showcase your fantastic fixes and contributions. - -## Have Fun! - -We hope you enjoy "The Hungry Bash" challenge and have a great time fixing and completing the script. This challenge will give you an opportunity to enhance your Bash scripting skills and provide a seamless restaurant order system for our customers. - -If you face any issues or have questions, feel free to reach out to us in the GitHub repository's issue section. - -Happy scripting and bon appétit! 🍽️ - ---- +## . + +# The Hungry Bash - Restaurant Order System Challenge + +Welcome to "The Hungry Bash" challenge! 🍔🍕🥗🥤 + +## Challenge Description + +In this challenge, you will be working on a Bash-based restaurant order system. The provided script, `restaurant_order.sh`, is partially broken and missing some crucial parts. Your task is to fix and complete the script to create a fully functional restaurant order system. + +### The Broken Script + +The `restaurant_order.sh` script is provided to you, but some essential parts are missing or not functioning correctly. Here are the broken parts: + +1. **Missing Menu Display**: The script is missing the code to read and display the menu from the `menu.txt` file. You need to implement the function to read the menu and display it to the customers. + +2. **Invalid User Input Handling**: The script is not handling invalid user input, such as entering a non-existent item number or negative quantities. You need to implement error handling to prompt users for valid inputs when necessary. + +3. **Total Bill Calculation**: The script is not calculating the correct total bill based on the customer's order. You need to implement the function to calculate the total bill accurately. + +### Your Task + +Your mission is to complete the `restaurant_order.sh` script and make it fully functional. Once you fix all the broken parts, the script should provide a smooth dining experience for our customers. + +## Getting Started + +1. Fork this repository to your GitHub account. + +2. Clone the forked repository to your local machine. + +3. Open the `menu.txt` file and verify that it contains a list of available food items, each on a separate line, with their corresponding prices in rupees, separated by a comma. + +4. Open the `restaurant_order.sh` script and begin your coding journey to fix the broken parts. + +## Submission + +Once you complete the script, commit your changes, and push them to your forked repository. Finally, submit a pull request to the original repository to showcase your fantastic fixes and contributions. + +## Have Fun! + +We hope you enjoy "The Hungry Bash" challenge and have a great time fixing and completing the script. This challenge will give you an opportunity to enhance your Bash scripting skills and provide a seamless restaurant order system for our customers. + +If you face any issues or have questions, feel free to reach out to us in the GitHub repository's issue section. + +Happy scripting and bon appétit! 🍽️ + +--- diff --git a/Challenges/Day_6/broken_resto/restaurant_order.sh b/Challenges/Day_6/broken_resto/restaurant_order.sh index 2f64c3e..4490578 100644 --- a/Challenges/Day_6/broken_resto/restaurant_order.sh +++ b/Challenges/Day_6/broken_resto/restaurant_order.sh @@ -4,24 +4,35 @@ function display_menu() { echo "Welcome to the Restaurant!" echo "Menu:" - # TODO: Read the menu from menu.txt and display item numbers and prices - # Format: 1. Burger - ₹120 - # 2. Pizza - ₹250 - # 3. Salad - ₹180 - # ... + echo "1. Burger - ₹120" + echo "2. Pizza - ₹250" + echo "3. Salad - ₹180" + echo "4. Soda, 40" + echo "5. Pasta, 180" + echo "6. Sandwich, 150" + echo "7. Coke, 50" + echo "8. Fries, 100" + echo "9. Ice Cream, 120" } +#to store the items +declare -A item +item[1]=120 +item[2]=250 +item[3]=180 +item[4]=40 +item[5]=180 +item[6]=150 +item[7]=50 +item[8]=100 +item[9]=120 + # Function to calculate the total bill function calculate_total_bill() { local total=0 - # TODO: Calculate the total bill based on the customer's order - # The order information will be stored in an array "order" - # The array format: order[] = - # Prices are available in the same format as the menu display - # Example: If the customer ordered 2 Burgers and 1 Salad, the array will be: - # order[1]=2, order[3]=1 - # The total bill should be the sum of (price * quantity) for each item in the order. - # Store the calculated total in the "total" variable. + for i in "${!order[@]}"; do + total=$(($total+(${order[$i]}*${item[$i]}))) + done echo "$total" } @@ -34,24 +45,30 @@ function handle_invalid_input() { display_menu # Ask for the customer's name -# TODO: Ask the customer for their name and store it in a variable "customer_name" +read -p "Please enter your name: " customer_name +if [ ${#customer_name} -eq 0 ]; then + echo "No name was entered" + exit 1 +fi # Ask for the order echo "Please enter the item number and quantity (e.g., 1 2 for two Burgers):" read -a input_order +if [ `expr ${#input_order[@]} % 2` -ne 0 ] + then echo "Please enter the quantity of the last item you mentioned." + exit 1 +fi + # Process the customer's order declare -A order for (( i=0; i<${#input_order[@]}; i+=2 )); do item_number="${input_order[i]}" quantity="${input_order[i+1]}" - # TODO: Add the item number and quantity to the "order" array + order[$item_number]=$quantity done # Calculate the total bill total_bill=$(calculate_total_bill) -# Display the total bill with a personalized thank-you message -# TODO: Display a thank-you message to the customer along with the total bill -# The message format: "Thank you, ! Your total bill is ₹." - +echo "Thank you $customer_name! Your total bill is ₹$total_bill." diff --git a/Challenges/Day_6/broken_search/new/no/hello.txt b/Challenges/Day_6/broken_search/new/no/hello.txt new file mode 100644 index 0000000..e69de29 diff --git a/Challenges/Day_6/broken_search/readmeFirst.md b/Challenges/Day_6/broken_search/readmeFirst.md index 4d21c30..e652281 100644 --- a/Challenges/Day_6/broken_search/readmeFirst.md +++ b/Challenges/Day_6/broken_search/readmeFirst.md @@ -1,36 +1,36 @@ -# Recursive Directory Search Challenge - -## Description - -The "Recursive Directory Search" challenge is part of the day-6. In this challenge, participants are tasked with creating a Bash script that performs a recursive search for a specific file within a given directory and its subdirectories. The script provided for this challenge is not functioning correctly, and participants must fix and improve it to achieve the desired behavior. - -## Challenge Details - -**Objective:** Your goal is to fix the provided Bash script, `recursive_search.sh`, and ensure it performs the recursive search as described below: - -- The script should take two command-line arguments: the directory to start the search and the target file name to find. -- The search should be recursive, meaning it should look for the target file not only in the specified directory but also in all its subdirectories and their subdirectories, and so on. -- When the target file is found, the script should print the absolute path of the file and then exit. -- Proper error handling should be in place to handle cases where the directory does not exist or the target file is not found. - -**Provided Files:** - -1. `recursive_search.sh`: The main script file that requires fixing and improvement. - -**Example Usage:** - -```bash -./recursive_search.sh test_files target.txt -``` - -If the target file `target.txt` exists within any of the subdirectories of `test_files`, the script should print the absolute path of the file. Otherwise, it should print "File not found: target.txt". - -**Note:** Ensure your script handles errors gracefully and provides informative messages to the user. - -## Tips - -- Take your time to understand the existing code before making changes. -- Make use of appropriate Bash commands and control structures to achieve the recursive search. -- Test your script thoroughly with different scenarios to ensure its correctness. - -Happy scripting! +# Recursive Directory Search Challenge + +## Description + +The "Recursive Directory Search" challenge is part of the day-6. In this challenge, participants are tasked with creating a Bash script that performs a recursive search for a specific file within a given directory and its subdirectories. The script provided for this challenge is not functioning correctly, and participants must fix and improve it to achieve the desired behavior. + +## Challenge Details + +**Objective:** Your goal is to fix the provided Bash script, `recursive_search.sh`, and ensure it performs the recursive search as described below: + +- The script should take two command-line arguments: the directory to start the search and the target file name to find. +- The search should be recursive, meaning it should look for the target file not only in the specified directory but also in all its subdirectories and their subdirectories, and so on. +- When the target file is found, the script should print the absolute path of the file and then exit. +- Proper error handling should be in place to handle cases where the directory does not exist or the target file is not found. + +**Provided Files:** + +1. `recursive_search.sh`: The main script file that requires fixing and improvement. + +**Example Usage:** + +```bash +./recursive_search.sh test_files target.txt +``` + +If the target file `target.txt` exists within any of the subdirectories of `test_files`, the script should print the absolute path of the file. Otherwise, it should print "File not found: target.txt". + +**Note:** Ensure your script handles errors gracefully and provides informative messages to the user. + +## Tips + +- Take your time to understand the existing code before making changes. +- Make use of appropriate Bash commands and control structures to achieve the recursive search. +- Test your script thoroughly with different scenarios to ensure its correctness. + +Happy scripting! diff --git a/Challenges/Day_6/broken_search/recursive_search.sh b/Challenges/Day_6/broken_search/recursive_search.sh index 501af36..8ae9ff0 100644 --- a/Challenges/Day_6/broken_search/recursive_search.sh +++ b/Challenges/Day_6/broken_search/recursive_search.sh @@ -8,7 +8,27 @@ fi search_directory=$1 target_file=$2 -# TODO: Implement the recursive search logic here +if [ ! -d "$search_directory" ]; then + echo "This directory is not present. Please enter an existing directory name." + exit 0 +fi + +search(){ + local abs="$1" + local t="$2" + for i in "$abs"/* + do + if [ -f "$i" ] && [ "$(basename "$i")" = "$t" ]; then + echo "Path of the file- $i" + exit 1 + elif [ -d "$i" ]; then + search "$i" "$t" + fi + done + +} + +abs_path=`cd "$search_directory" && pwd` +search "$abs_path" "$target_file" -echo "File not found: $target_file" -exit 1 +echo "File $target_file not found"