Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Comments and Explanations to Shell Script for Day 8 of 90DaysOfDevOps Challenge with images #340

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

Amitabh-DevOps
Copy link

@Amitabh-DevOps Amitabh-DevOps commented Dec 1, 2024

This pull request includes the following updates to the shell script for Day 8 of the 90DaysOfDevOps challenge:

  • Added detailed comments throughout the script to explain each section, including tasks related to:
    • Single-line and multi-line comments.
    • Echo command for printing messages.
    • User input handling using variables.
    • Built-in variables like date, pwd, whoami, and $HOME.
    • Use of wildcards to list .sh files in a specified directory.

The comments help clarify the purpose of each task and provide better understanding of the code for future reference.

Summary by CodeRabbit

  • New Features

    • Enhanced visuals and explanations for Shell Scripting and file permissions.
    • New scripts for directory creation, backups, permission management, and service automation.
    • Comprehensive bash script solution added for the Shell Scripting Challenge.
  • Documentation

    • Updated image references and improved content clarity across multiple documents.
    • Added new sections on package management and service management with detailed instructions.
  • Bug Fixes

    • Corrected image links and removed redundant references for clarity.

Copy link

coderabbitai bot commented Dec 1, 2024

Walkthrough

The changes across multiple solution.md files for Days 3 to 8 of a DevOps course involve updates primarily focused on enhancing content clarity, updating image references, and adding new scripts. Modifications include replacing external image URLs with local paths, refining explanations, and expanding sections on Shell Scripting, file permissions, and service management. New scripts have been introduced for various tasks, including directory creation, backups, and permission management. Overall, the updates aim to improve the instructional quality of the documents without altering the core tasks.

Changes

File Path Change Summary
2024/day03/solution.md Updated image links to local paths; modified presentation for Tasks 7 and 8; adjusted content for Task 6; added "hello world" at the end.
2024/day04/solution.md Enhanced explanations of Shell Scripting; removed old examples; added new images; clarified shebang line differences; updated task images.
2024/day05/solution.md Introduced new scripts: createDirectories.sh and backup.sh; detailed instructions for user management; updated LinkedIn profile link.
2024/day06/solution.md Expanded explanations on file permissions and ACLs; added new scripts for permission management; improved formatting and visual aids.
2024/day07/solution.md Changed title to "Day 7 Task"; added sections on package managers; restructured installation instructions for Docker and Jenkins; enhanced service management tasks.
2024/day08/solution.md Updated image references; added a new section with a complete bash script solution (day-08.sh); included detailed comments in the script.

Poem

🐇 In the land of scripts and code,
Changes made, the knowledge flowed.
From images bright to tasks anew,
Each line crafted, a clearer view.
With bash and scripts, we leap and bound,
In DevOps magic, joy is found! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Outside diff range and nitpick comments (3)
2024/day06/solution.md (1)

175-201: Add backup file rotation

Consider implementing backup file rotation to prevent overwriting existing backups.

Here's an improved implementation:

 #!/bin/bash

 <<Info
 Author      : Amitabh Soni
 Date        : 28/11/24
 Description : Creating a script that backs up the current permissions of files in a directory to a file.
 Info

+# Generate timestamp for backup file
+timestamp=$(date +%Y%m%d_%H%M%S)
+backup_file="permission_backup_${timestamp}.txt"
+
 # Prompt user for the directory path
 read -p "Enter the directory path to backup permissions: " dir_path

 # Check if the directory exists
 if [[ ! -d "$dir_path" ]]; then
    echo "Error: The directory '$dir_path' does not exist."
    exit 1
 fi

 # Get and backup the ACL permissions recursively
-getfacl -R "$dir_path" > permission_backup.txt
+getfacl -R "$dir_path" > "$backup_file"

 # Check if the command was successful
 if [[ $? -eq 0 ]]; then
-    echo "Permissions backed up successfully to permission_backup.txt"
+    echo "Permissions backed up successfully to $backup_file"
 else
    echo "Failed to backup permissions."
 fi
2024/day04/solution.md (2)

Line range hint 1-3: Consider adding specific DevOps examples

While the explanation of Shell Scripting is accurate, it would be more valuable for learners if you included concrete examples of common DevOps tasks that use shell scripts, such as:

  • Automated backup scripts
  • Log rotation and cleanup
  • Health check scripts
  • Deployment scripts
🧰 Tools
🪛 LanguageTool

[uncategorized] ~9-~9: Loose punctuation mark.
Context: ... using the Bash shell. - #!/bin/bash: Uses Bash as the interpreter. It suppor...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~10-~10: Loose punctuation mark.
Context: ...e arrays, and functions. - #!/bin/sh: Uses the Bourne shell. It’s more POSIX-...

(UNLIKELY_OPENING_PUNCTUATION)


Line range hint 1-28: Enhance document formatting for better readability

Consider these formatting improvements:

  • Add a table of contents
  • Use consistent heading levels (h1 for main title, h2 for tasks)
  • Add code blocks with syntax highlighting instead of just images

Example structure:

# Day 4: Basic Linux Shell Scripting for DevOps Engineers

## Table of Contents
- [Introduction](#introduction)
- [Task 1: Shell Scripting Basics](#task-1)
...

## Task 1: Shell Scripting Basics
🧰 Tools
🪛 LanguageTool

[uncategorized] ~9-~9: Loose punctuation mark.
Context: ... using the Bash shell. - #!/bin/bash: Uses Bash as the interpreter. It suppor...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~10-~10: Loose punctuation mark.
Context: ...e arrays, and functions. - #!/bin/sh: Uses the Bourne shell. It’s more POSIX-...

(UNLIKELY_OPENING_PUNCTUATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2071066 and b0e5173.

⛔ Files ignored due to path filters (126)
  • 2024/day03/image/task 1.png is excluded by !**/*.png
  • 2024/day03/image/task 10.png is excluded by !**/*.png
  • 2024/day03/image/task 11.png is excluded by !**/*.png
  • 2024/day03/image/task 12.png is excluded by !**/*.png
  • 2024/day03/image/task 2.png is excluded by !**/*.png
  • 2024/day03/image/task 3.png is excluded by !**/*.png
  • 2024/day03/image/task 4.png is excluded by !**/*.png
  • 2024/day03/image/task 5.png is excluded by !**/*.png
  • 2024/day03/image/task 6.png is excluded by !**/*.png
  • 2024/day03/image/task 66.png is excluded by !**/*.png
  • 2024/day03/image/task 7.png is excluded by !**/*.png
  • 2024/day03/image/task 8.png is excluded by !**/*.png
  • 2024/day03/image/task 9.png is excluded by !**/*.png
  • 2024/day03/image/task1.png is excluded by !**/*.png
  • 2024/day03/image/task10.png is excluded by !**/*.png
  • 2024/day03/image/task11.png is excluded by !**/*.png
  • 2024/day03/image/task12.png is excluded by !**/*.png
  • 2024/day03/image/task2.png is excluded by !**/*.png
  • 2024/day03/image/task3.png is excluded by !**/*.png
  • 2024/day03/image/task4.png is excluded by !**/*.png
  • 2024/day03/image/task5.png is excluded by !**/*.png
  • 2024/day03/image/task6.png is excluded by !**/*.png
  • 2024/day03/image/task7.1.png is excluded by !**/*.png
  • 2024/day03/image/task7.2.png is excluded by !**/*.png
  • 2024/day03/image/task8.1.png is excluded by !**/*.png
  • 2024/day03/image/task8.2.png is excluded by !**/*.png
  • 2024/day03/image/task9.png is excluded by !**/*.png
  • 2024/day04/image/task 1.png is excluded by !**/*.png
  • 2024/day04/image/task 11.png is excluded by !**/*.png
  • 2024/day04/image/task 2.png is excluded by !**/*.png
  • 2024/day04/image/task 3.png is excluded by !**/*.png
  • 2024/day04/image/task 4.png is excluded by !**/*.png
  • 2024/day04/image/task 5.png is excluded by !**/*.png
  • 2024/day04/image/task3.1.png is excluded by !**/*.png
  • 2024/day04/image/task3.2.png is excluded by !**/*.png
  • 2024/day04/image/task4.1.png is excluded by !**/*.png
  • 2024/day04/image/task4.2.png is excluded by !**/*.png
  • 2024/day04/image/task5.1.png is excluded by !**/*.png
  • 2024/day04/image/task5.2.png is excluded by !**/*.png
  • 2024/day05/image/task 1-2.png is excluded by !**/*.png
  • 2024/day05/image/task 1-3.png is excluded by !**/*.png
  • 2024/day05/image/task 1.png is excluded by !**/*.png
  • 2024/day05/image/task 2-1.png is excluded by !**/*.png
  • 2024/day05/image/task 2.png is excluded by !**/*.png
  • 2024/day05/image/task 3-1.png is excluded by !**/*.png
  • 2024/day05/image/task 3.png is excluded by !**/*.png
  • 2024/day05/image/task 4.png is excluded by !**/*.png
  • 2024/day05/image/task1.1.png is excluded by !**/*.png
  • 2024/day05/image/task1.2.png is excluded by !**/*.png
  • 2024/day05/image/task2.1.png is excluded by !**/*.png
  • 2024/day05/image/task2.2.png is excluded by !**/*.png
  • 2024/day05/image/task2.3.png is excluded by !**/*.png
  • 2024/day05/image/task3.1.png is excluded by !**/*.png
  • 2024/day05/image/task3.2.png is excluded by !**/*.png
  • 2024/day05/image/task3.3.png is excluded by !**/*.png
  • 2024/day05/image/task3.4.png is excluded by !**/*.png
  • 2024/day05/image/task3.5.png is excluded by !**/*.png
  • 2024/day05/image/task3.6.png is excluded by !**/*.png
  • 2024/day05/image/task4.1.png is excluded by !**/*.png
  • 2024/day05/image/task4.2.png is excluded by !**/*.png
  • 2024/day06/image/task1.1.png is excluded by !**/*.png
  • 2024/day06/image/task1.2.png is excluded by !**/*.png
  • 2024/day06/image/task1.3.png is excluded by !**/*.png
  • 2024/day06/image/task1.4.png is excluded by !**/*.png
  • 2024/day06/image/task1.png is excluded by !**/*.png
  • 2024/day06/image/task3.1.png is excluded by !**/*.png
  • 2024/day06/image/task3.png is excluded by !**/*.png
  • 2024/day06/image/task4-1.png is excluded by !**/*.png
  • 2024/day06/image/task4.1.1.png is excluded by !**/*.png
  • 2024/day06/image/task4.1.2.png is excluded by !**/*.png
  • 2024/day06/image/task4.2.1.png is excluded by !**/*.png
  • 2024/day06/image/task4.png is excluded by !**/*.png
  • 2024/day06/image/task5-1.png is excluded by !**/*.png
  • 2024/day06/image/task5-2.png is excluded by !**/*.png
  • 2024/day06/image/task5.1.png is excluded by !**/*.png
  • 2024/day06/image/task5.2.1.png is excluded by !**/*.png
  • 2024/day06/image/task5.2.2.png is excluded by !**/*.png
  • 2024/day06/image/task5.3.png is excluded by !**/*.png
  • 2024/day06/image/task5.png is excluded by !**/*.png
  • 2024/day06/image/task6-1.png is excluded by !**/*.png
  • 2024/day06/image/task6.1.png is excluded by !**/*.png
  • 2024/day06/image/task6.2.png is excluded by !**/*.png
  • 2024/day06/image/task6.png is excluded by !**/*.png
  • 2024/day07/image/task1-2.png is excluded by !**/*.png
  • 2024/day07/image/task1.1.png is excluded by !**/*.png
  • 2024/day07/image/task1.2.png is excluded by !**/*.png
  • 2024/day07/image/task1.3.png is excluded by !**/*.png
  • 2024/day07/image/task1.4.png is excluded by !**/*.png
  • 2024/day07/image/task1.png is excluded by !**/*.png
  • 2024/day07/image/task2.1.png is excluded by !**/*.png
  • 2024/day07/image/task3.2.png is excluded by !**/*.png
  • 2024/day07/image/task4.1.png is excluded by !**/*.png
  • 2024/day07/image/task4.2.png is excluded by !**/*.png
  • 2024/day07/image/task4.3.png is excluded by !**/*.png
  • 2024/day07/image/task4.png is excluded by !**/*.png
  • 2024/day07/image/task5-1.png is excluded by !**/*.png
  • 2024/day07/image/task5.1.1.png is excluded by !**/*.png
  • 2024/day07/image/task5.1.2.png is excluded by !**/*.png
  • 2024/day07/image/task5.2.1.png is excluded by !**/*.png
  • 2024/day07/image/task5.2.2.png is excluded by !**/*.png
  • 2024/day07/image/task5.png is excluded by !**/*.png
  • 2024/day07/image/task6-1.png is excluded by !**/*.png
  • 2024/day07/image/task6.1.png is excluded by !**/*.png
  • 2024/day07/image/task6.2.png is excluded by !**/*.png
  • 2024/day07/image/task6.png is excluded by !**/*.png
  • 2024/day07/image/taskj2.png is excluded by !**/*.png
  • 2024/day08/image/task1.1.png is excluded by !**/*.png
  • 2024/day08/image/task1.2.png is excluded by !**/*.png
  • 2024/day08/image/task1.png is excluded by !**/*.png
  • 2024/day08/image/task2.1.png is excluded by !**/*.png
  • 2024/day08/image/task2.2.png is excluded by !**/*.png
  • 2024/day08/image/task2.png is excluded by !**/*.png
  • 2024/day08/image/task3.1.png is excluded by !**/*.png
  • 2024/day08/image/task3.2.png is excluded by !**/*.png
  • 2024/day08/image/task3.png is excluded by !**/*.png
  • 2024/day08/image/task4.1.png is excluded by !**/*.png
  • 2024/day08/image/task4.2.png is excluded by !**/*.png
  • 2024/day08/image/task4.png is excluded by !**/*.png
  • 2024/day08/image/task5.1.png is excluded by !**/*.png
  • 2024/day08/image/task5.2.png is excluded by !**/*.png
  • 2024/day08/image/task5.png is excluded by !**/*.png
  • 2024/day08/image/task6.1.png is excluded by !**/*.png
  • 2024/day08/image/task6.2.png is excluded by !**/*.png
  • 2024/day08/image/task6.png is excluded by !**/*.png
  • 2024/day08/image/task7.1.png is excluded by !**/*.png
  • 2024/day08/image/task7.2.png is excluded by !**/*.png
📒 Files selected for processing (6)
  • 2024/day03/solution.md (1 hunks)
  • 2024/day04/solution.md (1 hunks)
  • 2024/day05/solution.md (1 hunks)
  • 2024/day06/solution.md (2 hunks)
  • 2024/day07/solution.md (1 hunks)
  • 2024/day08/solution.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • 2024/day03/solution.md
🧰 Additional context used
🪛 LanguageTool
2024/day08/solution.md

[duplication] ~28-~28: Possible typo: you repeated a word
Context: ...task2.2

  1. Variables
    • Variables in bash are used to store data and can ...

(ENGLISH_WORD_REPEAT_RULE)


[duplication] ~61-~61: Possible typo: you repeated a word
Context: ...k5.2](image/task5.2.png)

  1. Wildcards
    • Wildcards are special characters used to perform ...

(ENGLISH_WORD_REPEAT_RULE)

2024/day07/solution.md

[grammar] ~3-~3: The correct preposition appears to be “on”.
Context: ...temctl

What is a Package Manager in Linux?

In simpler words, a package m...

(IN_WINDOWS)


[uncategorized] ~11-~11: Use a comma before ‘but’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...is usually referred to as an application but it could be a GUI application, command ...

(COMMA_COMPOUND_SENTENCE)


[uncategorized] ~15-~15: Use a comma before ‘but’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ers differ based on the packaging system but the same packaging system may have more...

(COMMA_COMPOUND_SENTENCE_2)

2024/day05/solution.md

[uncategorized] ~13-~13: You might be missing the article “the” here.
Context: ...reating createDirectories.sh and adding below content :

``` bash

   #!/b...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~111-~111: You might be missing the article “a” here.
Context: ...

- Ensuring whether it creates backup in one minute or not : 

![task3.3...

(AI_EN_LECTOR_MISSING_DETERMINER_A)


[uncategorized] ~136-~136: “there” seems less likely than “their” (belonging to them).
Context: ...

- Creating users and printing there names : 

![task4.1](image/task4.1...

(AI_HYDRA_LEO_CPT_THERE_THEIR)

🪛 Markdownlint (0.35.0)
2024/day07/solution.md

3-3: Expected: h2; Actual: h3
Heading levels should only increment by one level at a time

(MD001, heading-increment)


46-46: null
Multiple headings with the same content

(MD024, no-duplicate-heading)


39-39: null
Bare URL used

(MD034, no-bare-urls)


74-74: null
Bare URL used

(MD034, no-bare-urls)

2024/day06/solution.md

47-47: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)


91-91: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)


96-96: Expected: 0; Actual: 3
Unordered list indentation

(MD007, ul-indent)


103-103: Expected: 0; Actual: 3
Unordered list indentation

(MD007, ul-indent)


35-35: null
Bare URL used

(MD034, no-bare-urls)


98-98: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


166-166: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)


204-204: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)

🔇 Additional comments (1)
2024/day04/solution.md (1)

14-28: Verify image references and accessibility

Let's ensure all referenced images exist in the correct location and are accessible.

✅ Verification successful

All image references are valid and accessible

All referenced images exist in the correct location (2024/day04/image/), have appropriate read permissions (644), and are properly named as referenced in the markdown file. No changes are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify existence of referenced images

# Check if the images exist
for img in "task3.1.png" "task3.2.png" "task4.1.png" "task4.2.png" "task5.1.png" "task5.2.png"; do
  if ! fd -p "2024/day04/image/$img" >/dev/null; then
    echo "Warning: Image $img not found in expected location"
  fi
done

# Check image file permissions
fd -p "2024/day04/image/*.png" -x stat -c "Image %n: permissions %a" {}

Length of output: 879


Script:

#!/bin/bash
# Let's try a different approach to verify the images
# First, let's check if the image directory exists
ls -la 2024/day04/image/

# Also, let's use find as an alternative to fd
find 2024/day04/image/ -name "*.png" -type f

Length of output: 734


# Task 3: Variable
# Initializing a variable 'sumation' and setting its value to 0
sumation=0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix typo and add input validation for arithmetic operations

  1. The variable name 'sumation' has a typo (should be 'summation')
  2. The arithmetic operation lacks input validation for non-numeric inputs
-sumation=0
+summation=0

-sumation=$(( num1 + num2 ))
+if [[ "$num1" =~ ^[0-9]+$ ]] && [[ "$num2" =~ ^[0-9]+$ ]]; then
+    summation=$(( num1 + num2 ))
+else
+    echo "Error: Please enter valid numbers"
+    exit 1
+fi

Also applies to: 106-106

Comment on lines +129 to +130
read -p "Enter dir path to print all .sh files in that dir : " sh_dir
cd ${sh_dir} && ls *.sh
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for directory navigation

The cd command could fail silently if the directory doesn't exist. Consider adding error handling.

-cd ${sh_dir} && ls *.sh
+if cd "${sh_dir}"; then
+    ls *.sh 2>/dev/null || echo "No .sh files found"
+else
+    echo "Error: Directory '${sh_dir}' not found or not accessible"
+    exit 1
+fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
read -p "Enter dir path to print all .sh files in that dir : " sh_dir
cd ${sh_dir} && ls *.sh
read -p "Enter dir path to print all .sh files in that dir : " sh_dir
if cd "${sh_dir}"; then
ls *.sh 2>/dev/null || echo "No .sh files found"
else
echo "Error: Directory '${sh_dir}' not found or not accessible"
exit 1
fi

Comment on lines +63 to +69
target_dir="/home/ubuntu/Day-05/backup"

# Backup filename
backup_file="${target_dir}/backup_${timestamp}.zip"

# Create zip backup
zip -r "$backup_file" "$1"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Make backup directory configurable and ensure it exists

The backup directory path should be configurable and the script should ensure it exists before creating backups.

-target_dir="/home/ubuntu/Day-05/backup"
+# Allow override through environment variable
+target_dir="${BACKUP_DIR:-/home/ubuntu/Day-05/backup}"
+
+# Ensure backup directory exists
+mkdir -p "$target_dir" || {
+    echo "Error: Cannot create backup directory"
+    exit 1
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
target_dir="/home/ubuntu/Day-05/backup"
# Backup filename
backup_file="${target_dir}/backup_${timestamp}.zip"
# Create zip backup
zip -r "$backup_file" "$1"
# Allow override through environment variable
target_dir="${BACKUP_DIR:-/home/ubuntu/Day-05/backup}"
# Ensure backup directory exists
mkdir -p "$target_dir" || {
echo "Error: Cannot create backup directory"
exit 1
}
# Backup filename
backup_file="${target_dir}/backup_${timestamp}.zip"
# Create zip backup
zip -r "$backup_file" "$1"

Comment on lines +27 to +30
# For loop to create directories iteratively
for i in $(seq $2 $3); do
mkdir "$1$i"
done
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add argument validation to createDirectories.sh

The script needs to validate:

  1. Number of arguments
  2. Whether arguments 2 and 3 are valid numbers
  3. Whether argument 3 is greater than argument 2
+# Validate number of arguments
+if [ "$#" -ne 3 ]; then
+    echo "Error: Three arguments required"
+    echo "Usage: $0 directory_name start_num end_num"
+    exit 1
+fi
+
+# Validate numeric arguments
+if ! [[ "$2" =~ ^[0-9]+$ ]] || ! [[ "$3" =~ ^[0-9]+$ ]]; then
+    echo "Error: Second and third arguments must be numbers"
+    exit 1
+fi
+
+# Validate range
+if [ "$3" -lt "$2" ]; then
+    echo "Error: End number must be greater than start number"
+    exit 1
+fi

# For loop to create directories iteratively
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# For loop to create directories iteratively
for i in $(seq $2 $3); do
mkdir "$1$i"
done
# Validate number of arguments
if [ "$#" -ne 3 ]; then
echo "Error: Three arguments required"
echo "Usage: $0 directory_name start_num end_num"
exit 1
fi
# Validate numeric arguments
if ! [[ "$2" =~ ^[0-9]+$ ]] || ! [[ "$3" =~ ^[0-9]+$ ]]; then
echo "Error: Second and third arguments must be numbers"
exit 1
fi
# Validate range
if [ "$3" -lt "$2" ]; then
echo "Error: End number must be greater than start number"
exit 1
fi
# For loop to create directories iteratively
for i in $(seq $2 $3); do
mkdir "$1$i"
done

Comment on lines +89 to +110
```bash
#!/bin/bash

<<Info
Author : Amitabh Soni
date : 30/11/24
description : This script is used to automate the stopping of Docker and Jenkins services.
Info

# Stopping Docker service
sudo systemctl stop docker

# Stopping Jenkins service
sudo systemctl stop jenkins

# Checking if the previous commands ran successfully
if [[ $? -eq 0 ]]; then
echo "Docker and Jenkins services have been stopped successfully."
else
echo "An error occurred while stopping Docker and Jenkins services."
fi
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding error handling for individual services

The script's error handling could be more granular. Currently, it only checks the final exit status, which might miss failures of individual services.

Consider this improved implementation:

 #!/bin/bash

 <<Info
 Author : Amitabh Soni
 date : 30/11/24
 description : This script is used to automate the stopping of Docker and Jenkins services.
 Info

-# Stopping Docker service
-sudo systemctl stop docker
-
-# Stopping Jenkins service
-sudo systemctl stop jenkins
-
-# Checking if the previous commands ran successfully
-if [[ $? -eq 0 ]]; then
-   echo "Docker and Jenkins services have been stopped successfully."
-else
-   echo "An error occurred while stopping Docker and Jenkins services."
-fi
+# Function to stop a service
+stop_service() {
+    local service=$1
+    if sudo systemctl stop "$service"; then
+        echo "$service stopped successfully"
+        return 0
+    else
+        echo "Failed to stop $service"
+        return 1
+    fi
+}
+
+# Stop services and track failures
+failed_services=()
+
+stop_service "docker" || failed_services+=("docker")
+stop_service "jenkins" || failed_services+=("jenkins")
+
+# Report final status
+if [ ${#failed_services[@]} -eq 0 ]; then
+    echo "All services stopped successfully"
+    exit 0
+else
+    echo "Failed to stop services: ${failed_services[*]}"
+    exit 1
+fi

Comment on lines +114 to +135
```bash
#!/bin/bash

<<Info
Author : Amitabh Soni
date : 30/11/24
description : This script is used to automate the starting of Docker and Jenkins services.
Info

# Starting Docker service
sudo systemctl start docker

# Starting Jenkins service
sudo systemctl start jenkins

# Checking if the previous commands ran successfully
if [[ $? -eq 0 ]]; then
echo "Docker and Jenkins services have been started successfully."
else
echo "An error occurred while starting Docker and Jenkins services."
fi
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Apply consistent error handling pattern

Similar to the stop script, the start script should handle individual service failures.

Consider this improved implementation:

 #!/bin/bash

 <<Info
 Author : Amitabh Soni
 date : 30/11/24
 description : This script is used to automate the starting of Docker and Jenkins services.
 Info

-# Starting Docker service
-sudo systemctl start docker
-
-# Starting Jenkins service
-sudo systemctl start jenkins
-
-# Checking if the previous commands ran successfully
-if [[ $? -eq 0 ]]; then
-    echo "Docker and Jenkins services have been started successfully."
-else
-    echo "An error occurred while starting Docker and Jenkins services."
-fi
+# Function to start a service
+start_service() {
+    local service=$1
+    if sudo systemctl start "$service"; then
+        echo "$service started successfully"
+        return 0
+    else
+        echo "Failed to start $service"
+        return 1
+    fi
+}
+
+# Start services and track failures
+failed_services=()
+
+start_service "docker" || failed_services+=("docker")
+start_service "jenkins" || failed_services+=("jenkins")
+
+# Report final status
+if [ ${#failed_services[@]} -eq 0 ]; then
+    echo "All services started successfully"
+    exit 0
+else
+    echo "Failed to start services: ${failed_services[*]}"
+    exit 1
+fi

Comment on lines +213 to +239
#!/bin/bash

<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : Script to restore file permissions from a backup file.
Info

# Prompt for the backup file path
read -p "Enter the backup file path: " backup_file

# Check if the backup file exists
if [[ ! -f "$backup_file" ]]; then
echo "Error: The backup file '$backup_file' does not exist."
exit 1
fi

# Restore the file permissions using the backup file
setfacl --restore="$backup_file"

# Check if the command was successful
if [[ $? -eq 0 ]]; then
echo "Permissions restored successfully from $backup_file"
else
echo "Failed to restore permissions."
fi
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add backup file validation

The script should validate that the backup file contains valid ACL entries before attempting to restore.

Here's an improved implementation:

 #!/bin/bash

 <<Info
 Author      : Amitabh Soni
 Date        : 28/11/24
 Description : Script to restore file permissions from a backup file.
 Info

 # Prompt for the backup file path
 read -p "Enter the backup file path: " backup_file

 # Check if the backup file exists
 if [[ ! -f "$backup_file" ]]; then
    echo "Error: The backup file '$backup_file' does not exist."
    exit 1
 fi

+# Validate backup file format
+if ! grep -q "^# file:" "$backup_file"; then
+    echo "Error: Invalid backup file format"
+    exit 1
+fi
+
+# Create a backup before restoration
+timestamp=$(date +%Y%m%d_%H%M%S)
+cp "$backup_file" "${backup_file}.${timestamp}.bak"
+
 # Restore the file permissions using the backup file
 setfacl --restore="$backup_file"

 # Check if the command was successful
 if [[ $? -eq 0 ]]; then
    echo "Permissions restored successfully from $backup_file"
+   echo "Original backup file saved as ${backup_file}.${timestamp}.bak"
 else
    echo "Failed to restore permissions."
 fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : Script to restore file permissions from a backup file.
Info
# Prompt for the backup file path
read -p "Enter the backup file path: " backup_file
# Check if the backup file exists
if [[ ! -f "$backup_file" ]]; then
echo "Error: The backup file '$backup_file' does not exist."
exit 1
fi
# Restore the file permissions using the backup file
setfacl --restore="$backup_file"
# Check if the command was successful
if [[ $? -eq 0 ]]; then
echo "Permissions restored successfully from $backup_file"
else
echo "Failed to restore permissions."
fi
```
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : Script to restore file permissions from a backup file.
Info
# Prompt for the backup file path
read -p "Enter the backup file path: " backup_file
# Check if the backup file exists
if [[ ! -f "$backup_file" ]]; then
echo "Error: The backup file '$backup_file' does not exist."
exit 1
fi
# Validate backup file format
if ! grep -q "^# file:" "$backup_file"; then
echo "Error: Invalid backup file format"
exit 1
fi
# Create a backup before restoration
timestamp=$(date +%Y%m%d_%H%M%S)
cp "$backup_file" "${backup_file}.${timestamp}.bak"
# Restore the file permissions using the backup file
setfacl --restore="$backup_file"
# Check if the command was successful
if [[ $? -eq 0 ]]; then
echo "Permissions restored successfully from $backup_file"
echo "Original backup file saved as ${backup_file}.${timestamp}.bak"
else
echo "Failed to restore permissions."
fi

Comment on lines +106 to +138
#!/bin/bash

<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script sets ACL permissions for a user on a given file, based on user input.
Info

# Getting username
read -p "Enter username: " user

# Getting file path
read -p "Enter a file path: " file_path

# Getting permission for the user
read -p "Enter the permission for user (e.g., rwx): " per

# Validate if the file exists
if [[ ! -e "$file_path" ]]; then
echo "Error: File '$file_path' does not exist."
exit 1
fi

# Setting ACL permission
setfacl -m u:$user:$per "$file_path"

# Checking the exit status of setfacl
if [[ $? -eq 0 ]]; then
echo "ACL permissions set successfully for user '$user' on file '$file_path'."
else
echo "Failed to set ACL permissions for user '$user' on file '$file_path'."
fi
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate ACL permission format

The script should validate that the provided permission string contains only valid ACL permissions.

Add permission validation:

 #!/bin/bash

 <<Info
 Author      : Amitabh Soni
 Date        : 28/11/24
 Description : This script sets ACL permissions for a user on a given file, based on user input.
 Info

 # Getting username
 read -p "Enter username: " user

 # Getting file path
 read -p "Enter a file path: " file_path

 # Getting permission for the user
 read -p "Enter the permission for user (e.g., rwx): " per

+# Validate permission format
+if ! [[ "$per" =~ ^[rwx-]{1,3}$ ]]; then
+    echo "Error: Invalid permission format. Use only r, w, x, or - characters"
+    exit 1
+fi
+
 # Validate if the file exists
 if [[ ! -e "$file_path" ]]; then
    echo "Error: File '$file_path' does not exist."
    exit 1
 fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script sets ACL permissions for a user on a given file, based on user input.
Info
# Getting username
read -p "Enter username: " user
# Getting file path
read -p "Enter a file path: " file_path
# Getting permission for the user
read -p "Enter the permission for user (e.g., rwx): " per
# Validate if the file exists
if [[ ! -e "$file_path" ]]; then
echo "Error: File '$file_path' does not exist."
exit 1
fi
# Setting ACL permission
setfacl -m u:$user:$per "$file_path"
# Checking the exit status of setfacl
if [[ $? -eq 0 ]]; then
echo "ACL permissions set successfully for user '$user' on file '$file_path'."
else
echo "Failed to set ACL permissions for user '$user' on file '$file_path'."
fi
```
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script sets ACL permissions for a user on a given file, based on user input.
Info
# Getting username
read -p "Enter username: " user
# Getting file path
read -p "Enter a file path: " file_path
# Getting permission for the user
read -p "Enter the permission for user (e.g., rwx): " per
# Validate permission format
if ! [[ "$per" =~ ^[rwx-]{1,3}$ ]]; then
echo "Error: Invalid permission format. Use only r, w, x, or - characters"
exit 1
fi
# Validate if the file exists
if [[ ! -e "$file_path" ]]; then
echo "Error: File '$file_path' does not exist."
exit 1
fi
# Setting ACL permission
setfacl -m u:$user:$per "$file_path"
# Checking the exit status of setfacl
if [[ $? -eq 0 ]]; then
echo "ACL permissions set successfully for user '$user' on file '$file_path'."
else
echo "Failed to set ACL permissions for user '$user' on file '$file_path'."
fi

Comment on lines +54 to +88
#!/bin/bash

<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script changes the permissions of all .txt files in a directory based on user input.
Info

# Prompting user for input
read -p "Enter the directory name: " dir_name
read -p "Enter permission value (numeric, e.g., 755): " num_value_per

# Validate if the directory exists
if [[ ! -d "$dir_name" ]]; then
echo "Error: Directory '$dir_name' does not exist."
exit 1
fi

# Check if .txt files exist in the directory
txt_files=("$dir_name"/*.txt)
if [[ ! -e "${txt_files[0]}" ]]; then
echo "Error: No .txt files found in directory '$dir_name'."
exit 1
fi

# Attempt to change file permissions for all .txt files
sudo chmod "$num_value_per" "$dir_name"/*.txt

# Checking the exit status
if [[ $? -eq 0 ]]; then
echo "Permissions changed successfully for all .txt files in '$dir_name'."
else
echo "Failed to change permissions for .txt files in '$dir_name'."
fi
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add validation for permission input

The script should validate that the permission value is a valid octal number.

Add input validation:

 #!/bin/bash

 <<Info
 Author      : Amitabh Soni
 Date        : 28/11/24
 Description : This script changes the permissions of all .txt files in a directory based on user input.
 Info

 # Prompting user for input
 read -p "Enter the directory name: " dir_name
 read -p "Enter permission value (numeric, e.g., 755): " num_value_per

+# Validate permission value
+if ! [[ "$num_value_per" =~ ^[0-7]{3}$ ]]; then
+    echo "Error: Invalid permission value. Please use a three-digit octal number (e.g., 755)"
+    exit 1
+fi
+
 # Validate if the directory exists
 if [[ ! -d "$dir_name" ]]; then
   echo "Error: Directory '$dir_name' does not exist."
   exit 1
 fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script changes the permissions of all .txt files in a directory based on user input.
Info
# Prompting user for input
read -p "Enter the directory name: " dir_name
read -p "Enter permission value (numeric, e.g., 755): " num_value_per
# Validate if the directory exists
if [[ ! -d "$dir_name" ]]; then
echo "Error: Directory '$dir_name' does not exist."
exit 1
fi
# Check if .txt files exist in the directory
txt_files=("$dir_name"/*.txt)
if [[ ! -e "${txt_files[0]}" ]]; then
echo "Error: No .txt files found in directory '$dir_name'."
exit 1
fi
# Attempt to change file permissions for all .txt files
sudo chmod "$num_value_per" "$dir_name"/*.txt
# Checking the exit status
if [[ $? -eq 0 ]]; then
echo "Permissions changed successfully for all .txt files in '$dir_name'."
else
echo "Failed to change permissions for .txt files in '$dir_name'."
fi
```
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 28/11/24
Description : This script changes the permissions of all .txt files in a directory based on user input.
Info
# Prompting user for input
read -p "Enter the directory name: " dir_name
read -p "Enter permission value (numeric, e.g., 755): " num_value_per
# Validate permission value
if ! [[ "$num_value_per" =~ ^[0-7]{3}$ ]]; then
echo "Error: Invalid permission value. Please use a three-digit octal number (e.g., 755)"
exit 1
fi
# Validate if the directory exists
if [[ ! -d "$dir_name" ]]; then
echo "Error: Directory '$dir_name' does not exist."
exit 1
fi
# Check if .txt files exist in the directory
txt_files=("$dir_name"/*.txt)
if [[ ! -e "${txt_files[0]}" ]]; then
echo "Error: No .txt files found in directory '$dir_name'."
exit 1
fi
# Attempt to change file permissions for all .txt files
sudo chmod "$num_value_per" "$dir_name"/*.txt
# Checking the exit status
if [[ $? -eq 0 ]]; then
echo "Permissions changed successfully for all .txt files in '$dir_name'."
else
echo "Failed to change permissions for .txt files in '$dir_name'."
fi

Comment on lines 5 to 8
- 'Shell Scripting is writing a series of commands in a script file to automate tasks in the Unix/Linux shell. For DevOps, shell scripting is crucial for automating repetitive tasks, managing system configurations, deploying applications, and integrating various tools and processes in a CI/CD pipeline. It enhances efficiency, reduces errors, and saves time.'

Example: Automating server setup
![image](https://github.com/Bhavin213/90DaysOfDevOps/blob/master/2024/day04/image/task%201.png)
![image](https://github.com/Bhavin213/90DaysOfDevOps/blob/master/2024/day04/image/task%2011.png)

Task 2: What is `#!/bin/bash`? Can we write `#!/bin/sh` as well?
- `#!/bin/bash` is called a "shebang" line. It indicates that the script should be run using the Bash shell.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add security best practices for shell scripts

Consider adding important security considerations when writing shell scripts:

  • Setting restrictive permissions (chmod 700)
  • Using set -euo pipefail for safer execution
  • Quoting variables to prevent word splitting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant