Day 6 Bash Scripting Challenge: The Mysterious Script

Table of contents

No heading

No headings in the article.

# 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 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.

Solution:

# Function to Decrypt and Reverse Content

mysterious_function() {

local input_file="$1"

local output_file="$2"

#!/bin/bash

# The Mysterious Script - Solution

# This script takes an input file, applies a series of mysterious transformations, and saves the result in an output file.

# Step 1: Decrypt the input file (ROT13 decryption)

tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file"

# Step 2: Reverse the content of the output file

rev "$output_file" > "reversed_temp.txt"

# Step 3: Generate a random number between 1 and 10

random_number=$(( ( RANDOM % 10 ) + 1 ))

# Step 4: Mystery loop - Reverse and Encrypt the content multiple times

for (( i=0; i<$random_number; i++ )); do

# Reverse the output file again

rev "reversed_temp.txt" > "temp_rev.txt"

# Encrypt the reversed content (ROT13 encryption)

tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp_rev.txt" > "temp_enc.txt"

# Swap the temporary files

mv "temp_enc.txt" "reversed_temp.txt"

done

# Step 5: Clean up temporary files

rm "temp_rev.txt"

}

# Main Script Execution

# Check if two arguments are provided

if [ $# -ne 2 ]; then

echo "Usage: $0 <input_file> <output_file>"

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 completion message

echo "The mysterious process is complete. Check the '$output_file' for the result!"

# 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.

#!/bin/bash

# Function to read and display the menu from menu.txt file

function display_menu() {

echo "Welcome to the Restaurant!"

echo "Menu:"

# Read the menu from menu.txt and display item numbers and prices

local item_number=1

while IFS= read -r line; do

name="$(echo "$line" | cut -d',' -f1)"

price="$(echo "$line" | cut -d',' -f2)"

echo "$item_number. $name - ₹$price"

((item_number++))

done < "menu.txt"

}

# Function to calculate the total bill

function calculate_total_bill() {

local total=0

# Calculate the total bill based on the customer's order

for item_number in "${!order[@]}"; do

price=$(sed -n "${item_number}p" "menu.txt" | cut -d',' -f2)

quantity="${order[$item_number]}"

((total += price * quantity))

done

echo "$total"

}

# Function to handle invalid user input

function handle_invalid_input() {

echo "Invalid input! Please enter a valid item number and quantity."

}

# Main script

display_menu

# Ask for the customer's name

echo -n "Please enter your name: "

read customer_name

# Ask for the order

echo "Please enter the item number and quantity (e.g., 1 2 for two Burgers):"

read -a input_order

# 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]}"

if [[ $item_number =~ ^[0-9]+$ && $quantity =~ ^[0-9]+$ ]]; then

order["$item_number"]="$quantity"

else

handle_invalid_input

exit 1

fi

done

# Calculate the total bill

total_bill=$(calculate_total_bill)

# Display the total bill with a personalized thank-you message

echo "Thank you, $customer_name! Your total bill is ₹$total_bill."

# 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.

#!/bin/bash

if [ $# -ne 2 ]; then

echo "Usage: ./recursive_search.sh <directory> <target_file>"

exit 1

fi

search_directory="$1"

target_file="$2"

# Function to perform recursive search for the target file

function search_recursive {

local current_dir="$1"

# Iterate through the contents of the current directory

for file in "$current_dir"/*; do

if [ -d "$file" ]; then

# If the current item is a directory, call the function recursively with the subdirectory

search_recursive "$file"

elif [ -f "$file" ] && [ "$(basename "$file")" = "$target_file" ]; then

# If the current item is a file and its name matches the target file, print its absolute path and exit

echo "File found: $file"

exit 0

fi

done

}

# Check if the provided directory exists

if [ ! -d "$search_directory" ]; then

echo "Error: Directory '$search_directory' not found."

exit 1

fi

# Start the recursive search by calling the search_recursive function with the provided search directory

search_recursive "$search_directory"

# If the loop completes without finding the target file, display a "File not found" message and exit with an error

echo "File not found: $target_file"

exit 1