diff --git a/Challenges/Day_1/my_bash_solution.md b/Challenges/Day_1/my_bash_solution.md new file mode 100644 index 0000000..2a9a14f --- /dev/null +++ b/Challenges/Day_1/my_bash_solution.md @@ -0,0 +1,129 @@ +## **Introduction:** + +Bash scripting is a powerful and versatile skill that allows you to automate tasks and perform complex operations using the command-line interface of a Unix-based operating system, such as Linux or macOS. Bash which stands for "Bourne Again Shell" is the default shell for many Unix-like systems and serves as a command interpreter for executing commands and scripts. + +Today we are going to cover the basics of Bash scripting. By the end of this challenge, we will be able to improve our understanding of bash scripting and will be able to create a bash script for the respective requirements. So, let's begin! + +## **Task 1: Comments** + +In bash scripts, comments are the non-executed part of the script. They provide useful information or explanations about the code. They play an important role in making the script more understandable not only for the author but also for the developers who might need to work with the script. + +Single-line comments: Single-line comments begin with (#) and extend till the end of the line. A line beginning with the # symbol will be completely ignored by the compiler. For example: + +```plaintext +#!/bin/bash + +# Task 1: Comments +# This is a single-line comment +echo "Hello World!" + +``` + +Multi-line comments: There are multiple ways through which you can mention multiple comments in a bash script. One such method is to use (:'). For example: + +```plaintext +#!/bin/bash +: ' +This is a multi-line comment block. +You can add as many lines as you want. +The code below will not be executed: + +echo "This line will not be executed." +' +echo "Hello World!" +``` + +## **Task 2: Echo** + +In bash, an `echo` command is a command used to output or display messages on the terminal. It is one of the most commonly used commands in bash script. Now let's create a bash script to print a message using `echo` command. + +```plaintext +#!/bin/bash + +# Task 2: Echo +# In this task, we will use the 'echo' to display a message. +echo "Let's explore the world of bash scripting!" +``` + +## **Task 3: Variables** + +In bash, variables are used to store data and values that can be referenced and manipulated throughout the script. They are a fundamental part of shell scripting and allow you to store temporary or permanent data. In this task, we will create a bash script that declares variables and assigns value to them. Here's how you declare and use variables in bash: + +```plaintext +#!/bin/bash + +# Task 3: Variables +# Remember to avaoid space between the '=' and variable +name="Tony Stark" +book="Think and Grow Rich" + +echo "My name is $name" +echo "And my favourite book is $book" +``` + +## **Task 4: Using Variables** + +In the previous task, we declared the variables. In this task, we will now make use of them to perform the given task. So we'll simply create two variables of type number and then print their sum. + +```plaintext +#!/bin/bash + +# Task 4: Using Variables +# In this task we will perform the addition of two numbers + +# Take the input for the variables from the user +read -p "Enter the first number: " num1 +read -p "Enter the second number: " num2 + +# Calculate the sum of two numbers +result=$((num1 + num2)) + +# Display the result +echo "The sum of two given numbers is: $result" +``` + +## **Task 5: Using Built-in Variables** + +Built-in variables are the special variables whose values are defined and maintained by the bash or the operating system. These variables are predefined and have specific names that are recognized by the shell. In this task, we will create a bash script that utilizes at least three different built-in variables to display relevant information. + +```plaintext +#!/bin/bash + +# Task 5: Built-in Variables +# In this task we will be utilizing built-in variables + +# $HOME represents the home directory of the current user +echo "Your home directory is: $HOME" + +# $USER holds the username of the current user +echo "Your username is: $USER" + +# $PWD represents the present working directory +echo "You are currently in: $PWD" + +# $HOSTNAME represents the current name of the host/machine +echo "Host name: $HOSTNAME" + +# $OSTYPE defines the operating system type +echo "Operating system type: $OSTYPE" +``` + +## **Task 6: Wildcards** + +Wildcards are special characters used to represent and match one or more filenames or paths. They are powerful tools that allow you to perform operations on multiple files or directories at once. In this task, we will create a bash script that utilizes wildcards to list all the files with a specific extension in a directory. + +```plaintext +#!/bin/bash + +# Task 6: Wildcards +# In this task, we will use wildcards to list files + +# Define the target directory +target_directory="/home/devops/" + +# List all files with a specific extension in the target directory +echo "Files with the '.txt' extension:" +ls "$target_directory"/*.txt +``` + + diff --git a/Challenges/Day_2/backup_with_rotation.sh b/Challenges/Day_2/backup_with_rotation.sh deleted file mode 100644 index 2c5e56f..0000000 --- a/Challenges/Day_2/backup_with_rotation.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -# Function to display usage information and available options -function display_usage { - echo "Usage: $0 /path/to/source_directory" -} - -# 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 - -# Directory path of the source directory to be backed up -source_dir="$1" - -# 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}" - - # Create the backup folder with the timestamped name - mkdir "$backup_dir" - echo "Backup created successfully: $backup_dir" -} - -# 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 - - # 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 deleted file mode 100644 index be62ca1..0000000 --- a/Challenges/Day_2/explorer.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/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 - - # Part 2: Character Counting - read -p "Enter a line of text (Press Enter without text to exit): " input - - # Exit if the user enters an empty string - if [ -z "$input" ]; then - echo "Exiting the Interactive Explorer. Goodbye!" - break - fi - - # 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_2/explorer_solution.md b/Challenges/Day_2/explorer_solution.md new file mode 100644 index 0000000..f8e238e --- /dev/null +++ b/Challenges/Day_2/explorer_solution.md @@ -0,0 +1,71 @@ +# **🌟 Introduction** + +Welcome to Day 2 of the #TWSBashBlaze Challenge. In this blog, we will create a bash script that serves as an interactive file and directory explorer. We'll create a script that will allow you to explore the files and directories in the current path interactively and also provide a character-counting feature for the user's input. So without wasting any time let's dive in! + +### **πŸ“‚ Part 1: File and Directory Exploration πŸ”** + +In this task, we are going to create a bash script explorer.sh which will display a welcome message and list all the files and directories in the current path upon execution. Our script will not only allow us to navigate through files and directories in the current path but also display their names and sizes in a human-readable format (e.g., KB, MB, GB). We'll achieve this functionality using the powerful ls command with appropriate options. The list of files and directories will be displayed in a loop until the user decides to exit the explorer. + +### **πŸ”€Part 2: Character Counting πŸ“** + +πŸ”On displaying the file and directory list, the script will prompt the user to enter a text-based input. The script will keep running in a loop until the user enters an empty string (πŸ‘‰the user presses Enter without any text). If the script is non-empty then it will count the number of characters present in the input. The character count will be displayed immediately after the input is passed. πŸ”€ + +Now let's dive in and write a script that fulfills all the above requirements!πŸ’»πŸš€ + + +```plaintext +#!/bin/bash + +# Part 1: File and Directory Exploration +echo "Welcome to the Interactive File and Directory Explorer!πŸ‘‹" + +# Run the infinite loop of while until user wants to exit +while true; do + + # Display the list of files and directories with their names and sizes + echo "Files and Directories in the Current Path:" + for item in *; do + if [ -e "$item" ]; then + size=$(ls -lh "$item" | awk '{print $5}') + echo "Name: $item Size: $size" + fi + done + + # Take the input from user to decide whether to continue looping + read -p "Enter a text input and press enter if you want to exit" input + + # Exit if the input is empty + if [ -z "$input" ]; then + echo "Exit the Interactive Explorer! Bbyee...See you!πŸ‘‹" + break + fi + + # Count the number of characters in an input text and then display the count + char_count=${#input} + echo "Character count: $char_count" + +done + +``` + + +### **πŸ” Usage:** + +Save the script in a file named explorer.sh. + +Make the script executable using the command: chmod +x explorer.sh. + +Execute the script using: ./explorer.sh. + + +### **πŸ”πŸ’»Output Screen:** + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/2b31ca89-5109-4323-93e9-b546b3f29964) + +# **πŸ“ Conclusion:** + +Congratulations! You have successfully completed Day 2 of the #TWSBashBlazeChallenge. You now have a versatile script that lets you explore files and directories in your current path, and it also includes a useful character-counting feature. πŸš€ I hope you enjoyed building this script and learning more about Bash scripting. Stay tuned for more exciting challenges in the upcoming days! + +Till then happy learning and keep exploring!🎈🌌 + + diff --git a/Challenges/Day_3/my_user_management_solution.md b/Challenges/Day_3/my_user_management_solution.md new file mode 100644 index 0000000..197f15b --- /dev/null +++ b/Challenges/Day_3/my_user_management_solution.md @@ -0,0 +1,272 @@ +## **πŸ‘©β€πŸ’»Introduction** + +Welcome back to the Day 3 of the #TWSBashBlazeChallenge! I hope you guys are enjoying the challenge and learning a lot through it. In this blog, we will create a bash script that provides options for managing user accounts on the system. The script will allow users to perform account-related tasks based on command-line arguments. + +Let's try to understand the real-life scenario based on this task. Let's suppose you are a system administrator and if we have a new employee joining your organization then you may need to add a new user. Similarly, if an employee leaves the organization this user needs to be deleted. In these cases, the system administrator has to perform these operations. So let's learn how to do it! + +## **πŸ”πŸ” Part 1: Account Creation πŸ’»πŸš€** + +In this task, we need to write a bash script that creates a user account. Here, the script should prompt the user to enter a new username and password. The script should check if the username already exists. If the user exists then the script should pass a statement throwing an error else it should create a user for you. Let's script it! + +``` +#!/bin/bash + +function if_user_exists() { + if id "$1" &>/dev/null; then + return 0 + else + return 1 + fi +} + +function create_user() { + read -p "Enter the new username: " username + if if_user_exists "$username"; then + echo "Error: The username '$username' already exists. Please choose a different username." + exit 1 + else + read -s -p "Enter the password for $username: " password + echo + sudo useradd "$username" --create-home --password "$password" + echo "User account '$username' created successfully." + fi +} + +``` + +## **πŸ—‘οΈπŸ‘‹ Part 2: Account Deletion πŸš«πŸ’»** + +Now, let's try to perform the deletion of a user account. The script should prompt the user to enter the username of the account to be deleted. Also, we need to ensure that the account already exists. If the account doesn't exist then we need to display an appropriate message and exit. + +``` +function if_user_exists() { + if id "$1" &>/dev/null; then + return 0 + else + return 1 + fi +} + +function delete_user() { + read -p "Enter the username to delete" username + if if_user_exists "$username"; then + sudo userdel --remove "$username" + echo "User account '$username' deleted successfully." + else + echo "Error: the username '$username' does not exist. Please enter a valid username." + exit 1 + fi +} + +``` + +## **πŸ”‘πŸ”„ Part 3: Password Reset πŸ”„πŸ”** + +Next, we'll implement the password reset feature. The script should ask for the username and the new password. If the username doesn't exist, the script should gracefully inform you and exit. + +``` +function if_user_exists() { + if id "$1" &>/dev/null; then + return 0 + else + return 1 + fi +} + +function reset_passwd() { + read -p "Enter the username to reset password: " username + if if_user_exists "$username"; then + read -s -p "Enter the password for $username: " password + echo "$username:$password" | sudo chpasswd + echo + echo "Password for user '$username' reset successfully." + else + echo "Error: The username '$username' does not exist. Please enter a valid username." + fi +} + +``` + +## **πŸ“‹πŸ‘₯ Part 4: List User Accounts πŸ“πŸ‘€** + +Now, let's try to implement a script that allows us to list all the user accounts along with their UIDs. + +``` +function list_users(){ + echo "User accounts on the system: " + sudo cat /etc/passwd | cut -d: -f1,3 | awk -F : '{printf "- %s (UID: %s)\n", $1, $2}' +} + +``` + +## **πŸ“šπŸ†˜ Part 5: Help and Usage Information πŸ“** + +Now finally we need to add a help option to display usage information and the available command-line options. So let's write a function for the same. + +``` +function display_usage(){ + echo "Usage: $0 [OPTIONS]" + echo "Options:" + printf "%-2s %-12s %-5s\n" " -c," "--create" "Create a new user account." + printf "%-2s %-12s %-5s\n" " -d," "--delete" "Delete an existing user account." + printf "%-2s %-12s %-5s\n" " -r," "--reset" "Reset password for an existing user account." + printf "%-2s %-12s %-5s\n" " -l," "--list" "List all user accounts on the system." + printf "%-2s %-12s %-5s\n" " -h," "--help" "Display this help and exit." +} + +``` + +## **βœ¨πŸ› οΈ Fully Functional Script πŸš€πŸ‘¨β€πŸ’»** + +``` +function display_usage(){ + echo "Usage: $0 [OPTIONS]" + echo "Options:" + printf "%-2s %-12s %-5s\n" " -c," "--create" "Create a new user account." + printf "%-2s %-12s %-5s\n" " -d," "--delete" "Delete an existing user account." + printf "%-2s %-12s %-5s\n" " -r," "--reset" "Reset password for an existing user account." + printf "%-2s %-12s %-5s\n" " -l," "--list" "List all user accounts on the system." + printf "%-2s %-12s %-5s\n" " -h," "--help" "Display this help and exit." +} + +function if_user_exists() { + if id "$1" &>/dev/null; then + return 0 + else + return 1 + fi +} + +function create_user() { + read -p "Enter the new username: " username + if if_user_exists "$username"; then + echo "Error: The username '$username' already exists. Please choose a different username." + exit 1 + else + read -s -p "Enter the password for $username: " password + echo + sudo useradd "$username" --create-home --password "$password" + echo "User account '$username' created successfully." + fi +} + +function delete_user() { + read -p "Enter the username to delete" username + if if_user_exists "$username"; then + sudo userdel --remove "$username" + echo "User account '$username' deleted successfully." + else + echo "Error: the username '$username' does not exist. Please enter a valid username." + exit 1 + fi +} + +function reset_passwd() { + read -p "Enter the username to reset password: " username + if if_user_exists "$username"; then + read -s -p "Enter the password for $username: " password + echo "$username:$password" | sudo chpasswd + echo + echo "Password for user '$username' reset successfully." + else + echo "Error: The username '$username' does not exist. Please enter a valid username." + fi +} + +function list_users(){ + echo "User accounts on the system: " + sudo cat /etc/passwd | cut -d: -f1,3 | awk -F : '{printf "- %s (UID: %s)\n", $1, $2}' +} + +# If no options provided, display usage information +if [[ "$#" -eq 0 ]]; then + echo "Error: No options provided." + display_usage + exit 1 +fi + +# Parse command-line options +while [[ $# -gt 0 ]]; do + case $1 in + -c | --create) + create_user + ;; + -d | --delete) + delete_user + ;; + -r | --reset) + reset_passwd + ;; + -l | --list) + list_users + ;; + -h | --help) + display_usage + exit 0 + ;; + *) + echo "Error: Invalid option '$1'." + display_usage + exit 1 + ;; + esac + shift +done + +``` + +## **Instructions for running the script:** + +Write the script and save it as `user_management.sh.` + +Make the script executable using chmod: `chmod +x user_management.sh`. + +Execute the script for the required options as follows: + +Create a new user: `./user_management.sh -c` + +Delete an existing user: `./user_management.sh -d` + +Reset user password: `./user_management.sh -r` + +List all user accounts: `./user_management.sh -l` + +Display help: `./user_management.sh -h` + +## **πŸ“ΊπŸ“· Interaction Output Screens πŸ–₯οΈπŸ“Έ** + +1. On executing `user_management.sh` + +![Screenshot 08-04-2023 23 51 05](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/45266a77-8d56-4226-b8e1-287f7bd9b6d8) + +2. For `./user_management.sh` -c or `./user_management.sh --create` + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/f97e4e1c-1e5c-4106-80f2-97ce0325f981) + +3. On running `./user_management.sh -d` or `./user_management.sh --delete` + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/c096e782-e7ef-428e-b102-bd7b8a0a1997) + +4. On executing `./user_management.sh -r` or `./user_management.sh --reset` + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/11c6ed73-053e-4848-9b24-0bddfdb0ff74) + +5. For listing the user accounts when we execute `./user_management.sh -l` or `./user_management.sh --list` + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/a49b24e5-a88b-47a8-8298-04e5ac307f2c) + +6. On executing the help option: + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/f83ce4f0-35df-4c84-8ae4-1904c2da80bc) + +## **πŸ“ Conclusion:** + +Now, you have a powerful Bash script to manage user accounts on your system. Whether you're administering a small network or a large organization, this script will save you time and effort, ensuring smooth user account management. + + + + + + + + diff --git a/Challenges/Day_4/my_monitor_process_solution.md b/Challenges/Day_4/my_monitor_process_solution.md new file mode 100644 index 0000000..02e16ee --- /dev/null +++ b/Challenges/Day_4/my_monitor_process_solution.md @@ -0,0 +1,172 @@ +## **πŸ“šIntroduction** + +πŸš€ Welcome to the world of Linux process monitoring! In this blog, we'll explore the power of Bash scripting πŸ“œ to ensure uninterrupted operations on your Linux system. In this fast-paced digital era, server uptime and application availability are vital for businesses and organizations to deliver seamless user experiences and maintain their competitive edge. As a Linux enthusiast or system administrator, you may have encountered situations where a specific process unexpectedly stops, leading to downtime and potential disruptions. + +Join us on this exciting journey as we learn how to create an efficient process monitoring solution that keeps critical applications running smoothly. πŸƒπŸ’¨ + +## **πŸ‘‰Monitoring the Process and Ensuring its uptime** + +πŸ‘©β€πŸ’» As a DevOps Engineer, I have come across many situations where I had to create, monitor, and ensure the uptime of the process. πŸ’Ό One of the most common issues faced by System administrators and DevOps engineers is monitoring a specific process's uptime and ensuring it remains active at all times. πŸ•°οΈ Performing this task manually is impractical and time-consuming. Hence needs to be automated using Bash script. πŸ€– So let's dive into the solution! πŸš€ + +## **πŸ‘‰Script** + +According to the requirement, the script should accept a command-line argument to specify the target process to monitor. + +For example: ./monitor_process.sh + +Process Existence Check: + +We need to check if the specified process is running on our system. If yes then we have to print the message accordingly. + +Create a file named `monitor_process.sh` + +``` +#!/bin/bash + +function check_process() { + + # Get the process name as a parameter of the function + process_name="$1" + + # Check if the process is running. + # If the process is running then return 0 else return 1. + if pgrep -x "$process_name" > /dev/null ; then + return 0 + else + return 1 +} + +``` + +Restarting the Process + +If the desired process is not running, implement a function that will restart the process. + +``` +function restart_process() { + # Considering the first parameter as the process name + process_name="$1" + + # Considering the number of attempts to restart the process. + attempts=3 + + for ((i=0; i + +``` + +Replace /path/to/monitor_process.sh with the actual path to the script, and with the process, you want to monitor. + +In our case, our crontab file will be like: + +``` + 0 * * * * monitor_process.sh nginx + +``` + +To check the cron job: + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/128c5b15-1c86-427b-8a6b-589abad28daa) + +## **✨ Fully Functional Script** + +``` +#!/bin/bash + +function check_process() { + + # Get the process name as a parameter of the function + process_name="$1" + + # Check if the process is running. + # If the process is running then return 0 else return 1. + if pgrep -x "$process_name" > /dev/null ; then + return 0 + else + return 1 +} + +function restart_process() { + # Considering the first parameter as the process name + process_name="$1" + + # Considering the number of attempts to restart the process. + attempts=3 + + for ((i=0; i "$summary_report" +``` + +## **βœ…Fully Functional Script!** + +``` +#!/bin/bash + +# Function is used to count the number of error messages +function count_error_msgs() { + + file_name="$1" + # Checks whether the file exists + if [ -f "$file_name" ]; then + # Use grep to match the entered text with the text in file + # -c is used to count the matched text + # -i stands to make the match case insensitive + error_count=$(grep -c -i "ERROR" "$file_name") + echo -e "\nTotal number of error messages in file $file_name: $error_count" + else + echo -e "\nError: File does not exist!" + exit 1 + fi +} + +function print_critical_lines() { + file_name="$1" + echo + echo -e "\nThe CRITICAL lines along with their line numbers are as follows: " + echo + if [ -f "$file_name" ]; then + mapfile -t critical_events < <(grep -n -i "CRITICAL" "$file_name") + for i in "${critical_events[@]}"; do + echo "$i" + done + else + echo -e "\nError: File not found..." + exit 1 + fi +} + +function display_top_error_messages() { + file_name="$1" + + if [ -f "$file_name" ]; then + declare -A error_msgs + while IFS= read -r line; do + error_msg=$(awk '{printf $4}' <<< "$line") + ((error_msgs["$error_msg"]++)) + done < <(grep -i "ERROR" $file_name) + echo + echo -e "The top 5 error messages are: " + echo + for msgs in "${!error_msgs[@]}"; do + echo "${error_msgs[$msgs]} $msgs" + done | sort -rn | head -n 5 + else + echo "Error: File not found..." + fi +} + +#Main Script +if [ "$#" -eq 0 ]; then + echo "Usage $0: Pass the log file as an argument you want to analyze!" + exit 1 +fi + +summary_report="summary-report-$(date).txt" +{ + echo -e "\n=========================Summary==============================" + echo -e "\nDate of Analysis: $(date)" + echo -e "\n--------------------------------------------------------------" + echo -e "\nLog File Name: $1" + echo -e "\n--------------------------------------------------------------" + echo -e "\nTotal Lines Processed: $(wc -l < "$1")" + echo -e "\n--------------------------------------------------------------" + count_error_msgs "$1" + echo -e "\n--------------------------------------------------------------" + display_top_error_messages "$1" + echo -e "\n--------------------------------------------------------------" + print_critical_lines "$1" + echo -e "\n--------------------------------------------------------------" +} > "$summary_report" + +mv "$1" analyzed_files +``` + +Instructions: + +1. Create a file named log_analyzer.sh using: `touch log_analyzer.sh` + +2. After this, add the above content to this log_analyzer.sh + +3. Make the file executable using: `chmod +x log_analyzer.sh` + +4. Then execute the script by passing a log file name as an argument. + +`./log_analyzer.sh sample_log.log` + +## **πŸ“ŠResulting OutputπŸ“‹** + +After execution of the above script, a report is generated. + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/69bde84d-74c7-4fc2-9350-094ec1234cbc) + +The report looks something like this: + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/5722762e-1838-4e39-88eb-1291899a8551) + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/2862bf36-ef24-496d-9d9e-7c2bb3500938) + +## **πŸ“Conclusion✨** + +In this way, we successfully created a bash script that analyzed the respective log file and also generated a summary report for the analysis. This tool will definitely help the DevOps Engineers and System Administrators for Log Analysis and Report Generation. + +Hope you found this blog helpful and informative! 🌟 + +Keep learning and keep exploring! πŸš€ + diff --git a/Challenges/Day_6/broken_myst/my_mystery_solution.md b/Challenges/Day_6/broken_myst/my_mystery_solution.md new file mode 100644 index 0000000..8e129c3 --- /dev/null +++ b/Challenges/Day_6/broken_myst/my_mystery_solution.md @@ -0,0 +1,358 @@ +## **🌟Introduction** + +Hey DevOps Enthusiasts, welcome back to our new blog. In this blog, you will encounter a mysterious Bash script named mystery.sh. The script lacks documentation and comments, leaving its purpose and functionality shrouded in mystery. The mission of this task is to unravel the secrets of this script, understand its objective, and improve it by adding comments and explanations. Let's dive in and try to understand and analyze the script! + +## **πŸ“’ Mysterious Bash Script for the Challenge** + +https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/blob/main/Challenges/Day_6/broken_myst/brokenday.md + +## **πŸ”Run the ScriptπŸƒβ€β™‚οΈ** + +On executing the script, it displays the message below and updates the 'output_file' and the 'reversed_temp.txt'. + +![image](https://github.com/gauri17-pro/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/60473255/7a6d1886-4534-4487-a224-f392eba6e493) + +## **🎯 Objective** + +The main objective of this task is to understand the `mystery.sh` file and accordingly add the comments and understandings. So, without wasting more time...let's get started! + +## **πŸ” Debugging and Decoding the Script πŸ“œ** + +On Debugging the code, we understood that there are no potential errors or bugs in the script. The script runs without any errors. + +The script begins with a shebang (#!/bin/bash) to specify the interpreter to be used (Bash in this case). + +Let's analyze the mysterious_function(). + +* The function takes two files as input parameters and stores the values in the variable input_file and output_file. + +* Encoding is performed on the input file where the characters in the file are rotated by 13 positions. + +* The content ofoutput_file is then reversed and stored in a file named reversed_temp.txt + +* A random number between 1 and 10 is generated and then the loop is executed random_number of times. + +* The loop is initiated by reversing the content of reversed_temp.txt and stored in temp_rev.txt + +* Again ROT13 algorithm is used to shift the characters by 13 positions. + +* Then the content of temp_rev.txt is moved to reversed_temp.txt + +* After exiting the loop, the temporary file temp_rev.txt is removed. + +Now considering the Main Script + +* While executing the script, two arguments containing the input and output files must be passed along with the shell script. If the number of arguments is not equal to 2 then the code exits by passing a meaningful message. + +* The first parameter must be an input file or the file you want to operate. + +* The second parameter is the output file which stores the result of the operation. + +* The script also checks the existence of an input file. If it doesn't exist then the script execution stops and it exits with a meaningful message. + +* If everything goes well, it then calls the function mysterious_function. + +## **πŸ“œ The Mysterious Bash Script** + +Let's add our understanding to the given script by adding the comments and explanations as follows: + +``` +#!/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() { + # Considering 2 parameters for the function and assigning the values to local variables + local input_file="$1" + local output_file="$2" + + # 'tr' is used to translate, delete, or squeeze characters from standard input or a file. + # tr 'A-Za-z' 'N-ZA-Mn-za-m' translates the range of characters from A-Z to N-Z and A-M and a-z to n-z and a-m + # In short, command below rotates the characters by 13 positions from the input file and then adds the result to the output file + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" + + # rev command is used to reverse the text it is passed + # Here, the content of the output_file is reversed and saved to reversed_temp.txt + rev "$output_file" > "reversed_temp.txt" + + # RANDOM is a built-in variable in Bash that generates a random integer between 0 and 32,767 each time it's accessed. + # The randomly created number is operated by mod to get the unit digit and hence the range of value will be from 0 to 9 + # The number is then added to 1 which gives the range of random_number + random_number=$(( ( RANDOM % 10 ) + 1 )) + + # Mystery loop: Reverses the content of the "reversed_temp.txt" file + # The loop runs for 'random_number' of times. + for (( i=0; i<$random_number; i++ )); do + # The reversed output of 'reversed_temp.txt' is stored in file 'temp_rev.txt' + rev "reversed_temp.txt" > "temp_rev.txt" + + # Rotation of characters by 13 positions is performed on file 'temp_rev.txt' to store the content in 'temp_enc.txt' + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp_rev.txt" > "temp_enc.txt" + + # Overwriting the file 'reversed_temp.txt' by newly encoded content + mv "temp_enc.txt" "reversed_temp.txt" + done + + # Clean up temporary files + rm "temp_rev.txt" + + # The mystery continues... + # The script will continue with more operations that you need to figure out! +} + +# 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!" + exit 1 +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!" +``` + +## **πŸš€ Optimizing the Code: Enhancing Efficiency πŸ› ** + +Since we are making use of a loop in the file mystery.sh it is not efficient. In order to make it more efficient we tried optimizing it by replacing the loop with the if condition as shown in the code below: + +``` +#!/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() { + # Considering 2 parameters for the function and assigning the values to local variables + local input_file="$1" + local output_file="$2" + + # 'tr' is used to translate, delete, or squeeze characters from standard input or a file. + # tr 'A-Za-z' 'N-ZA-Mn-za-m' translates the range of characters from A-Z to N-Z and A-M and a-z to n-z and a-m + # In short, command below rotates the characters by 13 positions from the input file and then adds the result to the output file + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" + + # rev command is used to reverse the text it is passed + # Here, the content of the output_file is reversed and saved to reversed_temp.txt + rev "$output_file" > "reversed_temp.txt" + + # RANDOM is a built-in variable in Bash that generates a random integer between 0 and 32,767 each time it's accessed. + # The randomly created number is operated by mod to get the unit digit and hence the range of value will be from 0 to 9 + # The number is then added to 1 which gives the range of random_number + random_number=$(( ( RANDOM % 10 ) + 1 )) + echo "$random_number" + + # We just replace the loop with if condition to optimize the code. + if [ $((random_number%2)) != 0 ]; then + # If a random_number is odd then the reversed_temp.txt will have the same content as that of input_file + cat "$input_file" > "reversed_temp.txt" + else + # If a random number is even then + # First, reverse the content of input_file and store it in temporary file 'temp.txt' + rev "$input_file" > "temp.txt" + # And then implement ROT13 algorithm on the temporary file to store it content in reversed_temp.txt + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp.txt" > "reversed_temp.txt" + fi + + # The mystery continues... + # The script will continue with more operations that you need to figure out! +} + +# 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!" + exit 1 +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!" +``` + +## **Since we are making use of a loop in the file mystery.sh it is not efficient. In order to make it more efficient we tried optimizing it by replacing the loop with the if condition as shown in the code below: + +#!/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() { + # Considering 2 parameters for the function and assigning the values to local variables + local input_file="$1" + local output_file="$2" + + # 'tr' is used to translate, delete, or squeeze characters from standard input or a file. + # tr 'A-Za-z' 'N-ZA-Mn-za-m' translates the range of characters from A-Z to N-Z and A-M and a-z to n-z and a-m + # In short, command below rotates the characters by 13 positions from the input file and then adds the result to the output file + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" + + # rev command is used to reverse the text it is passed + # Here, the content of the output_file is reversed and saved to reversed_temp.txt + rev "$output_file" > "reversed_temp.txt" + + # RANDOM is a built-in variable in Bash that generates a random integer between 0 and 32,767 each time it's accessed. + # The randomly created number is operated by mod to get the unit digit and hence the range of value will be from 0 to 9 + # The number is then added to 1 which gives the range of random_number + random_number=$(( ( RANDOM % 10 ) + 1 )) + echo "$random_number" + + # We just replace the loop with if condition to optimize the code. + if [ $((random_number%2)) != 0 ]; then + # If a random_number is odd then the reversed_temp.txt will have the same content as that of input_file + cat "$input_file" > "reversed_temp.txt" + else + # If a random number is even then + # First, reverse the content of input_file and store it in temporary file 'temp.txt' + rev "$input_file" > "temp.txt" + # And then implement ROT13 algorithm on the temporary file to store it content in reversed_temp.txt + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp.txt" > "reversed_temp.txt" + fi + + # The mystery continues... + # The script will continue with more operations that you need to figure out! +} + +# 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!" + exit 1 +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!" + +πŸŽ‰ Conclusion** + +Since we are making use of a loop in the file mystery.sh it is not efficient. In order to make it more efficient we tried optimizing it by replacing the loop with the if condition as shown in the code below: + +#!/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() { + # Considering 2 parameters for the function and assigning the values to local variables + local input_file="$1" + local output_file="$2" + + # 'tr' is used to translate, delete, or squeeze characters from standard input or a file. + # tr 'A-Za-z' 'N-ZA-Mn-za-m' translates the range of characters from A-Z to N-Z and A-M and a-z to n-z and a-m + # In short, command below rotates the characters by 13 positions from the input file and then adds the result to the output file + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" + + # rev command is used to reverse the text it is passed + # Here, the content of the output_file is reversed and saved to reversed_temp.txt + rev "$output_file" > "reversed_temp.txt" + + # RANDOM is a built-in variable in Bash that generates a random integer between 0 and 32,767 each time it's accessed. + # The randomly created number is operated by mod to get the unit digit and hence the range of value will be from 0 to 9 + # The number is then added to 1 which gives the range of random_number + random_number=$(( ( RANDOM % 10 ) + 1 )) + echo "$random_number" + + # We just replace the loop with if condition to optimize the code. + if [ $((random_number%2)) != 0 ]; then + # If a random_number is odd then the reversed_temp.txt will have the same content as that of input_file + cat "$input_file" > "reversed_temp.txt" + else + # If a random number is even then + # First, reverse the content of input_file and store it in temporary file 'temp.txt' + rev "$input_file" > "temp.txt" + # And then implement ROT13 algorithm on the temporary file to store it content in reversed_temp.txt + tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp.txt" > "reversed_temp.txt" + fi + + # The mystery continues... + # The script will continue with more operations that you need to figure out! +} + +# 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!" + exit 1 +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!" + +πŸŽ‰ Conclusion + +Congratulations! We have added all the required comments and explanations to the script wherever necessary. We also tried optimizing the code and tried to make it more efficient by removing the loop. + +Hope you enjoyed this blog and learned something new! πŸ“šβœ¨ + +Keep learning and Happy Scripting! πŸš€πŸ–₯