diff --git a/Self-solutions/Day_1/day1_challange_solution.sh b/Self-solutions/Day_1/day1_challange_solution.sh new file mode 100755 index 0000000..a80d04d --- /dev/null +++ b/Self-solutions/Day_1/day1_challange_solution.sh @@ -0,0 +1,95 @@ +#!/bin/bash + +##################################################################### +# Script Name: day1_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: July 31, 2023 +# Description: This script contains solution for all the 6 tasks for Day-1 part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day1_challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +# set -x Used it while debugging the script. + +#Task 1: Comments +#In bash scripts, comments are used to add explanatory notes or disable certain lines of code. Your task is to create a bash script with comments explaining what the script does. + +#Task_1 Solution: + ## This is a comment in shell script + + +#Task 2: Echo +#The echo command is used to display messages on the terminal. Your task is to create a bash script that uses echo to print a message of your choice. + +#Task-2 solution: +echo "This is Day-1 task-2 echo example" + + +#Task 3: Variables +#Variables in bash are used to store data and can be referenced by their name. Your task is to create a bash script that declares variables and assigns values to them. + +#Task 4: Using Variables +#Now that you have declared variables, let's use them to perform a simple task. Create a bash script that takes two variables (numbers) as input and prints their sum using those variables. + + +#Task-3 and Task-4 solution: +#note: Don't give space after '=' operand below , otherwise you will get errors +a=3 +b=7 +c=$(( a + b )) #The double parentheses are used for arithmetic evaluation in Bash. It allows you to perform arithmetic operations on numerical values within the shell script. +echo "sum of two elements $a + $b = $c" + +#Improvising the task3&4 +echo "enter the first number: " +read a + +echo "enter the second number: " +read b + +c=$(( a + b )) +echo "sum of $a and $b is $c" + + + +#Task 5: Using Built-in Variables +#Bash provides several built-in variables that hold useful information. Your task is to create a bash script that utilizes at least three different built-in variables to display relevant information. + +#task-5 solution: +echo "Disk usage: " +df -h + +echo "Checking exit status of the last commmand $?" #If we get 0 means successful + +echo "To install any module, let's say net-tools for checking network connections" +sudo apt-get update +sudo apt-get install net-tools + + +echo "Checking network connections: " +echo "Display listening TCP and UDP ports" +netstat -tuln + +#netstat -rn # Display routing table + + +echo "Checking DNS resolution of google: " +nslookup www.google.com + +echo "Checking if service is running: " +systemctl status ssh + + +#Task-6 Wildcards +#Wildcards are special characters used to perform pattern matching when working with files. Your task is to create a bash script that utilizes wildcards to list all the files with a specific extension in a directory. + +#Task-6 solution: +#Wildcards in shell scripting are special characters used to represent one or more characters in a file or directory name. example ls, mv, cp rm etc. commonly used wildcards in shell scripting: + +#* (Asterisk): Represents zero or more characters. +ls *.txt # *.txt matches all files with the .txt extension within the directory. + +#Wildcards are powerful tools for batch processing and manipulating files in shell scripts. However, it's essential to be cautious when using wildcards, especially with commands like rm. + + diff --git a/Self-solutions/Day_1/day_1_solution_practice.sh b/Self-solutions/Day_1/day_1_solution_practice.sh new file mode 100755 index 0000000..3655715 --- /dev/null +++ b/Self-solutions/Day_1/day_1_solution_practice.sh @@ -0,0 +1,140 @@ +#!/bin/bash + +set -x + +#Task 1: Comments +#In bash scripts, comments are used to add explanatory notes or disable certain lines of code. Your task is to create a bash script with comments explaining what the script does. + +#Task_1 Solution: + ## This is a comment in shell script + + +#Task 2: Echo +#The echo command is used to display messages on the terminal. Your task is to create a bash script that uses echo to print a message of your choice. + +#Task-2 solution: +echo "This is Day-1 task-2 echo example" + + +#Task 3: Variables +#Variables in bash are used to store data and can be referenced by their name. Your task is to create a bash script that declares variables and assigns values to them. + +#Task 4: Using Variables +#Now that you have declared variables, let's use them to perform a simple task. Create a bash script that takes two variables (numbers) as input and prints their sum using those variables. + + +#Task-3 and Task-4 solution: +#note: Don't give space after '=' operand below , otherwise you will get errors +a=3 +b=7 +c=$(( a + b )) #The double parentheses are used for arithmetic evaluation in Bash. It allows you to perform arithmetic operations on numerical values within the shell script. +echo "sum of two elements $a + $b = $c" + +#Improvising the task3&4 +echo "enter the first number: " +read a + +echo "enter the second number: " +read b + +c=$(( a + b )) +echo "sum of $a and $b is $c" + + + +#Task 5: Using Built-in Variables +#Bash provides several built-in variables that hold useful information. Your task is to create a bash script that utilizes at least three different built-in variables to display relevant information. + +#task-5 solution: +echo "Disk usage: " +df -h + +echo "Checking exit status of the last commmand $?" #If we get 0 means successful + +echo "To install any module, let's say net-tools for checking network connections" +sudo apt-get update +sudo apt-get install net-tools + + +echo "Checking network connections: " +echo "Display listening TCP and UDP ports" +netstat -tuln + +#netstat -rn # Display routing table + + +echo "Checking DNS resolution of google: " +nslookup www.google.com + +echo "Checking if service is running: " +systemctl status ssh + +## There are more as follows + +#Download a file using wget: wget http://example.com/file.zip +#Generate an SSH key pair: ssh-keygen -t rsa -b 4096 +#Install Python dependencies from requirements.txt: pip install -r requirements.txt +#Monitor log files in real-time: tail -f /var/log/ +#Search for a specific pattern in files: grep "pattern" /path/to/files/* +#Check the content of a log file: cat /var/log/ +#Use curl to test APIs or URLs: curl http://example.com/api +#Restart a service: sudo systemctl restart +#Create a backup of a directory using tar: tar -czvf backup.tar.gz /path/to/directory +#View running processes: ps aux +#Monitor system resources with top: top +#to check and list all runnig services: systemctl list-units --type=service --state=running + #service --status all +## Display the name of the script file: echo "Script name: $0" +# Display the number of arguments passed to the script: echo "Number of arguments: $#" +## Display the process ID of the current script: echo "Process ID of the current script: $$" +## Display the parent process ID: echo "Parent process ID: $PPID" +## Display the username of the current user: echo "Current username: $USER" +# Display the home directory of the current user: echo "Home directory: $HOME" +# Display the exit status of the last executed command: echo "Exit status of the last command: $?" +## Display the current working directory: echo "Current working directory: $PWD" + + +## + + +#Task-6 Wildcards +#Wildcards are special characters used to perform pattern matching when working with files. Your task is to create a bash script that utilizes wildcards to list all the files with a specific extension in a directory. + +#Task-6 solution: +#Wildcards in shell scripting are special characters used to represent one or more characters in a file or directory name. example ls, mv, cp rm etc. commonly used wildcards in shell scripting: + +#* (Asterisk): Represents zero or more characters. +#Example: *.txt matches all files with the .txt extension. +ls *.txt + +#? (Question Mark): Represents a single character. +#Example: file?.txt matches files like file1.txt, file2.txt, etc. + +#[] (Square Brackets): Represents a range of characters or a character set. +#Example: [aeiou] matches any vowel character. +#Example: [0-9] matches any digit. + +#! (Exclamation Mark): Negates the pattern. +#Example: !*.txt matches all files except those with the .txt extension. + +#{} (Curly Braces): Used for brace expansion, which generates multiple strings based on a pattern. +#Example: file{1,2,3}.txt expands to file1.txt, file2.txt, file3.txt. + +#Wildcards are powerful tools for batch processing and manipulating files in shell scripts. However, it's essential to be cautious when using wildcards, especially with commands like rm, to avoid accidentally deleting important files. Always double-check your patterns before executing commands with wildcards. + + + + + + + + + + + + + + + + + diff --git a/Self-solutions/Day_1/readme.txt b/Self-solutions/Day_1/readme.txt new file mode 100644 index 0000000..6178965 --- /dev/null +++ b/Self-solutions/Day_1/readme.txt @@ -0,0 +1 @@ +please run 'day1_challange_solution.sh' diff --git a/Self-solutions/Day_2/day2.0_challange_solution.sh b/Self-solutions/Day_2/day2.0_challange_solution.sh new file mode 100755 index 0000000..d89d96a --- /dev/null +++ b/Self-solutions/Day_2/day2.0_challange_solution.sh @@ -0,0 +1,81 @@ +#!/bin/bash + +##################################################################### +# Script Name: day_2.0_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 1, 2023 +# Description: This script contains solution for Day 2 Bash Scripting Challenge - Interactive File and Directory Explorer part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day_2.0__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +####################Day 2 Bash Scripting Challenge - Interactive File and Directory Explorer +#Welcome to Day 2 of the Bash Scripting Challenge! In this challenge, you will create a bash script that serves as an interactive file and directory explorer. The script will allow you to explore the files and directories in the current path and provide a character counting feature for the user's input. + +####################Challenge Description####################### +#The script will have two main parts: + +###################Part 1: File and Directory Exploration + #Upon execution without any command-line arguments, the script will display a welcome message and list all the files and directories in the current path. + #For each file and directory, the script will print its name and size in human-readable format (e.g., KB, MB, GB). This information will be obtained using the 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 + #After displaying the file and directory list, the script will prompt the user to enter a line of text. + #The script will read the user's input until an empty string is entered (i.e., the user presses Enter without any text). + #For each line of text entered by the user, the script will count the number of characters in that line. + #The character count for each line entered by the user will be displayed. + + +#################Example Interaction + #$ ./explorer.sh + #Welcome to the Interactive File and Directory Explorer! + +#Files and Directories in the Current Path: +#- file1.txt (100 KB) +#- dir1 (2 MB) +#- script.sh (3 KB) +#... + +#Enter a line of text (Press Enter without text to exit): Hello, this is a sample line. +#Character Count: 27 + +#Enter a line of text (Press Enter without text to exit): Another line to count. +#Character Count: 25 + +#Enter a line of text (Press Enter without text to exit): +#Exiting the Interactive Explorer. Goodbye! + +echo +echo "Welcome to the Interactive File and Directory Explorer!" +while true; do #this will be worked as infinite loop in shell script + + echo + echo "Files and Directories in the Current Path:" + + #This extract each and every directory and file in current path using $PWD and for loop to iterate over every item + for directoryItemName in $PWD/*; do + + if [ -f "$directoryItemName" ]; then #checking if the item is file then we use ls -lh to get the file size + directoryItemSize=$(ls -lh "$directoryItemName" | awk '{print $5}') #we are using awk command to extract the 5th item from ls output + + elif [ -d "$directoryItemName" ]; then #here we are checking if item is directory or not using -d + directoryItemSize=$(du -sh "$directoryItemName" | awk '{print $1}') #using du -sh for directory size as ls will not gonna give and extractin g the first argument for size. + fi + + directoryItemBaseName=$(basename "$directoryItemName") #using basename keyword to extract only name of the file otherwise we wil get whole path + echo "- $directoryItemBaseName ($directoryItemSize)" + + done + echo + read -p "Enter a line of text (Press Enter without text to exit): " userInputString #taking input from the user using read with -p argument , if we mention -p then it will ask the prompt and store the input to variable. + if [ -z "$userInputString" ]; then #checking if the statement length is 0 using -z means it is empty then we will exit the infinite loop. + echo "Exiting the Interactive Explorer. Goodbye!" + echo + break #using break to exit from the infinite loop + else + characterCountOfStatement=$( echo -n "$userInputString" | wc -c ) #counting the characters of a statement using wc -c means word count with -c argument for character counting. and we are eliminating newline with the help of echo -n here. + echo "Character Count: $characterCountOfStatement" + fi +done diff --git a/Self-solutions/Day_2/day2.1_challange_solution.sh b/Self-solutions/Day_2/day2.1_challange_solution.sh new file mode 100755 index 0000000..a163cb6 --- /dev/null +++ b/Self-solutions/Day_2/day2.1_challange_solution.sh @@ -0,0 +1,80 @@ +#!/bin/bash + +#set -x #For debugging the script + +##################################################################### +# Script Name: day2.1_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 1, 2023 +# Description: This script contains solution for Day 2.1 Directory Backup with Rotation part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day2.1_challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + + +################################Directory Backup with Rotation + #This is another challenge for Day 2 of the Bash Scripting Challenge! In this challenge, you will create a bash script that performs a backup of a specified directory and implements a rotation mechanism to manage backups. + + + +################################Challenge Description +#Your task is to create a bash script that takes a directory path as a command-line argument and performs a backup of the directory. The script should create timestamped backup folders and copy all the files from the specified directory into the backup folder. + +#Additionally, the script should implement a rotation mechanism to keep only the last 3 backups. This means that if there are more than 3 backup folders, the oldest backup folders should be removed to ensure only the most recent backups are retained. + +#The script will create a timestamped backup folder inside the specified directory and copy all the files into it. It will also check for existing backup folders and remove the oldest backups to keep only the last 3 backups. + + +directoryPath=$1 #taking first command line argument + +#this is to check the count of files starts with 'backup' name. +backupFilesCount=$( ls -1 /root| grep -c ^backup ) +# ls -1 : It will give the filenames in single column +# '|' pipe symbol will transfer the output of previous command to next command here +# grep -c ^backup: grep command useful to search the file starts with 'backup' name. ^ symbol useful to starts with and -c will give the count. + + +if [ $backupFilesCount -le 3 ]; then + + #trying to give the unique name for every backup including date as below format as a file name + # Get the current date to use in the backup filename + backup_date=$(date +%Y%m%d%H%M%S) #date with the format YYYYMMDDHHMMSS + + #defining full name of the backup file + backup_filename="backup_$backup_date.tar.gz" + + # Create the backup archive using tar + tar -czf /root/"$backup_filename" --absolute-names "$directoryPath" + + #first parameter is the backup file name with it's path to store + # second paramter is from where we should take the backup(path of the backup folder) + #here we are taking backup from curent folder + #-cvzf is for compressinng the tar file and we can use -xvzf is for extractinv the tar file . + #just a first letter change c:Create a new archive , x:extract here, z:Compress the archive using gzip, f:Specify the name of the archive file, v:output will of backup directorypath will be return.will display the names of the files it is processing as it performs its operations. + echo "Backup created: $directoryPath/$backup_filename" + +elif [ $backupFilesCount -gt 3 ]; then #this elif block will check for count is 3 + oldestFileName=$( ls -1 /root | grep ^backup | sort -nr | tail -1 ) + #ls -1 /root: will give us the filenames in single column + #grep ^backup: extract only files starts with backup' from previous command output + #sort -nr: # sorting the files in descending order , for ascending we can use sort -n + #tail -1 : taking the last file name from previous output as oldest file will be in descending order + rm /root/"$oldestFileName" #removing the oldest file + echo "Removed the oldest file: $oldestFileName" + #creating the backup with the new file name, it's like replacing the new file after deleting the old file among 3 backup files. + backup_date=$(date +%Y%m%d%H%M%S) + backup_filename="backup_$backup_date.tar.gz" + tar -czf /root/"$backup_filename" --absolute-names "$directoryPath" + echo "Backup created: $directoryPath/$backup_filename" +fi + + + +#############################Improvised and automated this script using crontab like below as an advancement. +#I have used crontab to schedule the backup script to run every day at 11:50 PM. +#opened the crontab configuration by running : crontab -e and then you can run crontab -l to see the scheduled configurations. +#and added the following line at the end of the crontab file: 50 23 * * * /root/shell-scripting-projects/2_backup_log_files.sh >> /root/backup_log.log 2>&1 + #the >> operator appends the output (both standard output and standard error) of the cron job to the specified log file (backup_log.log). The 2>&1 part ensures that both standard output (1) and standard error (2) are redirected to the log file. + diff --git a/Self-solutions/Day_2/day_2.0_solution_practice.sh b/Self-solutions/Day_2/day_2.0_solution_practice.sh new file mode 100755 index 0000000..d8770a6 --- /dev/null +++ b/Self-solutions/Day_2/day_2.0_solution_practice.sh @@ -0,0 +1,184 @@ +#!/bin/bash + +##################################################################### +# Script Name: day_2.0_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 1, 2023 +# Description: This script contains solution for Day 2 Bash Scripting Challenge - Interactive File and Directory Explorer part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day_2.0__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +####################Day 2 Bash Scripting Challenge - Interactive File and Directory Explorer +#Welcome to Day 2 of the Bash Scripting Challenge! In this challenge, you will create a bash script that serves as an interactive file and directory explorer. The script will allow you to explore the files and directories in the current path and provide a character counting feature for the user's input. + +####################Challenge Description####################### +#The script will have two main parts: + +###################Part 1: File and Directory Exploration + #Upon execution without any command-line arguments, the script will display a welcome message and list all the files and directories in the current path. + #For each file and directory, the script will print its name and size in human-readable format (e.g., KB, MB, GB). This information will be obtained using the 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 + #After displaying the file and directory list, the script will prompt the user to enter a line of text. + #The script will read the user's input until an empty string is entered (i.e., the user presses Enter without any text). + #For each line of text entered by the user, the script will count the number of characters in that line. + #The character count for each line entered by the user will be displayed. + + +#################Example Interaction + #$ ./explorer.sh + #Welcome to the Interactive File and Directory Explorer! + +#Files and Directories in the Current Path: +#- file1.txt (100 KB) +#- dir1 (2 MB) +#- script.sh (3 KB) +#... + +#Enter a line of text (Press Enter without text to exit): Hello, this is a sample line. +#Character Count: 27 + +#Enter a line of text (Press Enter without text to exit): Another line to count. +#Character Count: 25 + +#Enter a line of text (Press Enter without text to exit): +#Exiting the Interactive Explorer. Goodbye! + +echo +echo "Welcome to the Interactive File and Directory Explorer!" +while true; do #this will be worked as infinite loop in shell script + + echo + echo "Files and Directories in the Current Path:" + + #This extract each and every directory and file in current path using $PWD and for loop to iterate over every item + for directoryItemName in $PWD/*; do + + if [ -f "$directoryItemName" ]; then #checking if the item is file then we use ls -lh to get the file size + directoryItemSize=$(ls -lh "$directoryItemName" | awk '{print $5}') #we are using awk command to extract the 5th item from ls output + + elif [ -d "$directoryItemName" ]; then #here we are checking if item is directory or not using -d + directoryItemSize=$(du -sh "$directoryItemName" | awk '{print $1}') #using du -sh for directory size as ls will not gonna give and extractin g the first argument for size. + fi + + directoryItemBaseName=$(basename "$directoryItemName") #using basename keyword to extract only name of the file otherwise we wil get whole path + echo "- $directoryItemBaseName ($directoryItemSize)" + + done + echo + read -p "Enter a line of text (Press Enter without text to exit): " userInputString #taking input from the user using read with -p argument , if we mention -p then it will ask the prompt and store the input to variable. + if [ -z "$userInputString" ]; then #checking if the statement length is 0 using -z means it is empty then we will exit the infinite loop. + echo "Exiting the Interactive Explorer. Goodbye!" + echo + break #using break to exit from the infinite loop + else + characterCountOfStatement=$( echo -n "$userInputString" | wc -c ) #counting the characters of a statement using wc -c means word count with -c argument for character counting. and we are eliminating newline with the help of echo -n here. + echo "Character Count: $characterCountOfStatement" + fi +done + + +######################################################################################### +#practice-1 +#practicing infinite loop in shell script +#!/bin/bash + +while true; do + # Your code inside the infinite loop goes here + + # Example: Ask the user for input + read -p "Enter 'exit' to stop the loop: " user_input + + # Check if the user wants to exit + if [ "$user_input" = "exit" ]; then + echo "Exiting the loop." + break + fi +done + + + + +#practice-2 +#check if the user entered an empty string by comparing the input variable with an empty string. +#!/bin/bash + +read -p "Enter your input: " user_input + +if [ -z "$user_input" ]; then + echo "You entered an empty string." +else + echo "Your input is: $user_input" +fi + +#practice-3: +#practicing to get the file and directory size in a human-readable format. The -h option (or --human-readable) formats the sizes into KB, MB, GB, etc. +#!/bin/bash + +# Replace "path/to/your/file_or_directory" with the actual file or directory path +path="path/to/your/file_or_directory" + +# Get the size in human-readable format using du command +size=$(du -h "$path") + +echo "Size of $path: $size" + +#practice-4: +#practicing to get all the files and directories in specified path and get the size and its basename +#!/bin/bash + +# Replace "path/to/your/directory" with the actual directory path +directory="path/to/your/directory" + +# Loop through each item in the directory +for item in "$directory"/*; do + # Get the size and name of the file/directory in human-readable format using ls command + size=$(ls -lh "$item" | awk '{print $5}') + name=$(basename "$item") + + echo "$name: $size" +done + + +#practice-5: +#practiciing to get the word count of statment +#!/bin/bash + +# Replace "Your statement here" with the actual statement you want to count characters for +statement="Your statement here" + +# Get the character count using echo and wc commands +char_count=$(echo -n "$statement" | wc -c) + +echo "Character count: $char_count" + + +#practice-6: +#practicing to check if the directory is having file or directory and extracting size based on the type and using ls -h and du -sh for file and directory accordingly. +#!/bin/bash + +# Replace "path/to/your/directory" with the actual directory path +directory="path/to/your/directory" + +# Loop through each item in the directory +for item in "$directory"/*; do + if [ -f "$item" ]; then + # For files, get the size using ls command + size=$(ls -lh "$item" | awk '{print $5}') + elif [ -d "$item" ]; then + # For directories, get the size using du command + size=$(du -sh "$item" | awk '{print $1}') + fi + + name=$(basename "$item") + + echo "$name: $size" +done + + + + + diff --git a/Self-solutions/Day_2/day_2.1_solution_practice.sh b/Self-solutions/Day_2/day_2.1_solution_practice.sh new file mode 100644 index 0000000..822b515 --- /dev/null +++ b/Self-solutions/Day_2/day_2.1_solution_practice.sh @@ -0,0 +1,134 @@ +#!/bin/bash + +#this script is to take the backup of logs or any work you done. and this is automated shell script that runs everyday at 11:50PM IST using cronttab + +#trying to give the uniqueu name for every backup including date as below format as a file name +# Get the current date to use in the backup filename +backup_date=$(date +%Y%m%d%H%M%S) + +#defining full name of the backup file +backup_filename="backup_$backup_date.tar.gz" + +# Create the backup archive using tar +tar -cvzf /root/"$backup_filename" ./* #first parameter is the backup file name with it's path to store + # second paramter is from where we should take the backup(path of the backup folder) + #here we are taking backup from curent folder + #-cvzf is for compressinng the tar file and -xvzf is for extractinv the tar file . + #just a first letter change c:compress , x:extract here. + +echo "Backup created: $backup_filename" + + +#I have used crontab to schedule the backup script to run every day at 11:50 PM. +#opened the crontab configuration by running : crontab -e and then you can run crontab -l to see the scheduled configurations. +#and added the following line at the end of the crontab file: 50 23 * * * /root/shell-scripting-projects/2_backup_log_files.sh >> /root/backup_log.log 2>&1 + #the >> operator appends the output (both standard output and standard error) of the cron job to the specified log file (backup_log.log). The 2>&1 part ensures that both standard output (1) and standard error (2) are redirected to the log file. +#then it will run this at specified timing and take the logs or your work done. +#To remove all crontab schedules for the current user, you can use the crontab -r command. +#Remember to be cautious when editing crontab, especially with root privileges, as incorrect changes can cause unintended issues with your scheduled tasks. Double-check your changes before saving the crontab file. so prepare first and setup at once. + + +#practice-1 +#practicing the To count the number of files that start with "backup" in a given directory path +#!/bin/bash + +# Directory path where you want to count files +directory="/path/to/directory" + +# Count the number of files starting with "backup" in the directory +file_count=$(ls -1 "$directory" | grep -c '^backup') + +echo "Number of files starting with 'backup': $file_count" + +#practice-2 +#To find the oldest file among the files starting with "backup" in the given directory path +#!/bin/bash + +# Directory path where you want to find the files +directory="/path/to/directory" + +# Find all files starting with "backup" and get their modification time +oldest_file=$(find "$directory" -maxdepth 1 -name 'backup*' -type f -exec stat -c '%Y %n' {} + | sort -n | head -n 1 | awk '{print $2}') + +echo "The oldest file among files starting with 'backup' is: $oldest_file" + + + +#practice-3 +#To get the files in descending order (from the newest to the oldest) among the files starting with "backup" in the given directory path +#!/bin/bash + +# Directory path where you want to find the files +directory="/path/to/directory" + +# Find all files starting with "backup" and get their modification time +newest_file=$(find "$directory" -maxdepth 1 -name 'backup*' -type f -exec stat -c '%Y %n' {} + | sort -nr | head -n 1 | awk '{print $2}') + +echo "The newest file among files starting with 'backup' is: $newest_file" +#The modification made to the script is in the sort -nr part, where we use the -r flag to sort the files in reverse (descending) order based on their modification time. + +#practice-4 +#practicing the conditional statements in shell scripting +#!/bin/bash + +# Variables for comparison +number1=10 +number2=20 + +# Check if the numbers are equal +if [ "$number1" == "$number2" ]; then + echo "Numbers are equal" +else + echo "Numbers are not equal" +fi + +# Check if the numbers are not equal +if [ "$number1" != "$number2" ]; then + echo "Numbers are not equal" +else + echo "Numbers are equal" +fi + +# Check if number1 is greater than number2 +if [ "$number1" -gt "$number2" ]; then + echo "Number1 is greater than Number2" +else + echo "Number1 is not greater than Number2" +fi + +# Check if number1 is less than or equal to number2 +if [ "$number1" -le "$number2" ]; then + echo "Number1 is less than or equal to Number2" +else + echo "Number1 is not less than or equal to Number2" +fi + + +#practice-5 +#following the below approach to avoice the error tar: Removing leading `/' from member names +tar -czf your_archive.tar.gz --absolute-names /path/to/files + +#practice-6 +#practicing the command line arguments in shell scripting + +#These arguments allow you to provide input to the script at runtime, enabling you to customize the script's behavior based on the provided values. +# In bash (a popular shell used on many Unix-like systems), you can access command-line arguments using special variables: + +# $0: The name of the script itself. +# $1, $2, $3, ...: These variables represent the first, second, third, and so on, command-line arguments passed to the script. +# $@: Represents all the command-line arguments as separate words. It is an array-like variable. +# $#: The number of command-line arguments passed to the script. +#!/bin/bash + +# Access command-line arguments using $1 and $2 +echo "First argument: $1" +echo "Second argument: $2" + +# Access all command-line arguments using $@ +echo "All arguments: $@" + +# Access the number of arguments using $# +echo "Number of arguments: $#" + + + diff --git a/Self-solutions/Day_2/readme.txt b/Self-solutions/Day_2/readme.txt new file mode 100644 index 0000000..7aa766b --- /dev/null +++ b/Self-solutions/Day_2/readme.txt @@ -0,0 +1,47 @@ +please run 'day2.0_challange_solution.sh' and day2.1_challange_solution.sh + + +sample output for the script day2.0_challange_solution.sh: + +~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_2# ./day2.0_challange_solution.sh + +Welcome to the Interactive File and Directory Explorer! + +Files and Directories in the Current Path: +- day2.0_challange_solution.sh (4.6K) +- day_2.0_solution_practice.sh (4.6K) +- readme.txt (40) +- temp (8.0K) + +Enter a line of text (Press Enter without text to exit): Hello, this is a sample line. +Character Count: 29 + +Files and Directories in the Current Path: +- day2.0_challange_solution.sh (4.6K) +- day_2.0_solution_practice.sh (4.6K) +- readme.txt (40) +- temp (8.0K) + +Enter a line of text (Press Enter without text to exit): Another line to count. +Character Count: 22 + +Files and Directories in the Current Path: +- day2.0_challange_solution.sh (4.6K) +- day_2.0_solution_practice.sh (4.6K) +- readme.txt (40) +- temp (8.0K) + +Enter a line of text (Press Enter without text to exit): +Exiting the Interactive Explorer. Goodbye! + + +sample output for the script day2.1_challange_solution.sh +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_2# ./day2.1_challange_solution.sh /root/backup_directory/ +Backup created: /root/backup_directory//backup_20230801124651.tar.gz +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_2# ./day2.1_challange_solution.sh /root/backup_directory/ +Backup created: /root/backup_directory//backup_20230801124655.tar.gz +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_2# ./day2.1_challange_solution.sh /root/backup_directory/ +Backup created: /root/backup_directory//backup_20230801124656.tar.gz +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_2# ./day2.1_challange_solution.sh /root/backup_directory/ +Removed the oldest file: backup_20230801124651.tar.gz +Backup created: /root/backup_directory//backup_20230801124657.tar.gz diff --git a/Self-solutions/Day_3/day3_challenge_solution.sh b/Self-solutions/Day_3/day3_challenge_solution.sh new file mode 100755 index 0000000..0207a43 --- /dev/null +++ b/Self-solutions/Day_3/day3_challenge_solution.sh @@ -0,0 +1,337 @@ +#!/bin/bash +#set -x + +##################################################################### +# Script Name: day_3_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 2, 2023 +# Description: This script contains solution for Day 3 User Account Management as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day_3__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +######################################## Day-3 Challenge: User Account Management ######################################### + +#In this challenge, you will create a bash script that provides options for managing user accounts on the system. The script should allow users to perform various user account-related tasks based on command-line arguments. + +###########Part 1: Account Creation +#Implement an option -c or --create that allows the script to create a new user account. The script should prompt the user to enter the new username and password. + +#Ensure that the script checks whether the username is available before creating the account. If the username already exists, display an appropriate message and exit gracefully. + +#After creating the account, display a success message with the newly created username. + + +#########Part 2: Account Deletion +#Implement an option -d or --delete that allows the script to delete an existing user account. The script should prompt the user to enter the username of the account to be deleted. + +#Ensure that the script checks whether the username exists before attempting to delete the account. If the username does not exist, display an appropriate message and exit gracefully. + +#After successfully deleting the account, display a confirmation message with the deleted username. + + +#########Part 3: Password Reset +#Implement an option -r or --reset that allows the script to reset the password of an existing user account. The script should prompt the user to enter the username and the new password. + +#Ensure that the script checks whether the username exists before attempting to reset the password. If the username does not exist, display an appropriate message and exit gracefully. + +#After resetting the password, display a success message with the username and the updated password. + + +########Part 4: List User Accounts +#Implement an option -l or --list that allows the script to list all user accounts on the system. The script should display the usernames and their corresponding user IDs (UID). + + +#######Part 5: Help and Usage Information +#Implement an option -h or --help that displays usage information and the available command-line options for the script. + + +#######Bonus Points (Optional) +#If you want to challenge yourself further, you can add additional features to the script, such as: + +#Displaying more detailed information about user accounts (e.g., home directory, shell, etc.). +#Allowing the modification of user account properties (e.g., username, user ID, etc.). +#Remember to handle errors gracefully, provide appropriate user prompts, and add comments to explain the logic and purpose of each part of the script. + +#Created function to list out the User Options to run the script. +displayUserOptions() { + +echo +echo "Usage: ./day3_challenge_solution.py [OPTIONS]" +echo "Options:" +echo " -c, --create Create a new user account" +echo " -d, --delete Delete an existing user account" +echo " -r, --reset Reset password for an existing user account" +echo " -l, --list List all user accounts on the system" +echo " -h, --help Display this help and exit." +echo +echo "For Bonus features please use below options" +echo " -ui, --userinfo Display more information about an existed user account" +echo " -mu, --modusername Modify username for an existing user account" +echo " -muid, --moduserid Modify user ID for an existing user account" +echo " -mh, --modhome Modify home directory for an existing user account " +echo " -ms, --modshell Modify default shell for an existing user account" +echo " -mg, --modgroup Modify group for an existing user account " +echo " -mpa, --modpassage Modify password expiration date for an existing user account" +echo " -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account" +echo + +} + +#Created the function to check if user is already existed or not in our system. +is_user_exists() { + userName=$1 #we are taking function argument that passess while calling the function. here $1 is for user provided username input. + + if grep -q "^$userName:" /etc/passwd; then #checking if user already present or not using + #grep command checks if the specifie username that starts with $username is present in /etc/passwd output or #not + #-q option with grep will hide the output of the grep command + + return 0 #returning 0 if username is present otherwise sending 1. + else + return 1 + fi + +} + +displayUserOptions #calling this function to dispay the user option at the time of script runs. + +userOption=$1 #taking the command line 1st argument that pass while running the script and assigning to this variable. + +if [ "$userOption" == "-c" ] || [ "$userOption" == "--create" ]; then #putting two conditions to check -c OR --create user option to create the user. + + + read -p "Enter username to create the user account: " usernameByUser #taking username input from the user to create the user + is_user_exists "$usernameByUser" #passing the user provided username to the is_user_exists function as a command line argument. + + if [ $? -eq 0 ]; then #here $? - checks the previous command output and get the output here and i am comparing it with 0 means user exists. + echo "user $usernameByUser already existed, so please create the user with different username!" + exit 0 #existing from the script with safe command exit 0 with successful run if user exists. + fi + read -p "Enter password to create the account: " passwordByUser + sudo useradd "$usernameByUser" #using useradd command with sudo permission to create the user + echo "$usernameByUser:$passwordByUser" | chpasswd #assigning the user provided password to created user using echo to pass the output to chpasswd. + echo "user account $usernameByUser has been created successfully!" + +elif [ "$userOption" == "-d" ] || [ "$userOption" == "--delete" ]; then + read -p "Enter username to delete the user account: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + sudo userdel "$usernameByUser" #deleting the user if user is present in our system. + echo "user account $usernameByUser has been deleted successfully!" + else + echo "user $usernameByUser is not existed, so please choose a existed user to delete!" + + fi +elif [ "$userOption" == "-r" ] || [ "$userOption" == "--reset" ]; then + read -p "Enter username to reset the user account password: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + echo "please enter a new password for $usernameByUser: " + read -s newUserPasswordByUser #read with -s option is to take the password by hiding the password to user while he enters. + echo "$usernameByUser:$newUserPasswordByUser" | chpasswd #same as assiging the password but also can useful to reset the new password. + echo "user account $usernameByUser reset password has completed successfully!" + else + echo "user $usernameByUser is not existed, so please choose a existed user to reset the password!" + + fi + +elif [ "$userOption" == "-l" ] || [ "$userOption" == "--list" ]; then + + echo "Username UID GID" #printing the username UID(User ID) and GID(group ID) + echo "---------------------" + while IFS=: read -r username _ uid gid _; do #here IFS is a field seperator which seperates the all the lines output of /etc/passwd with : semicolon + echo "$username $uid $gid" # that's why I have put = and : with IFS means IFS=: and after seperating with semicolon i have read the + done < /etc/passwd #username with $1 first argument , assigning $2 argument with dummy variable as we don't need this for now + #$2 argument is password basically and $3 and $4 arguments are UID and GID and leaving remaining arguments + #with _ dummy variable till end and we are iterating till last line so using while loop to iterate and + #/etc/passwd contains all the usernames with details. + + + #we can also implement this with other approach as below + # Using awk to print the username (first field) and UID (third field) + #awk -F: '{print "Username:", $1, "UID:", $3}' /etc/passwd + #here we use awk with print to display the output to terminal +elif [ "$userOption" == "-h" ] || [ "$userOption" == "--help" ]; then + displayUserOptions #displaying the user options for help option. + + +#From here is for the bonus features!! +elif [ "$userOption" == "-ui" ] || [ "$userOption" == "--userinfo" ]; then + + read -p "Enter username to know more information about the user account: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + sudo grep "$usernameByUser" /etc/passwd | awk -F: '{print "\n Username: ", $1"\n", "UID:", $3"\n", "Home directory:", $6"\n", "Default shell:", $7"\n"}' + #the above command will print out the Username, UID, Home directory, Default shell details for specific user. + #here we are using grep to find the username in the /etc/passwd file this will return whole line of output with : semicolon + #passing the output via | pipe symbol to awk command and here we are splitting line of output with : semicolon using F: + #using print to display the output to the terminal + else + echo "user $usernameByUser is not existed, so please choose an existed user to display more information about the user!" + + fi + + +elif [ "$userOption" == "-mu" ] || [ "$userOption" == "--modusername" ]; then #this is for modification of username + + read -p "Enter username that you wanted to modify it's username: " oldUsernameByUser + + is_user_exists "$oldUsernameByUser" + + if [ $? -eq 0 ]; then + read -p "Enter new username that you wanted to modify for user $oldUsernameByUser: " newUsernameByUser #taking new username as a input + sudo usermod -l "$newUsernameByUser" "$oldUsernameByUser" #using -l option with usermod to change the username + echo "Successfully Updated the username from $oldUsernameByUser to $newUsernameByUser! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's username!" + fi + + +elif [ "$userOption" == "-muid" ] || [ "$userOption" == "--moduserid" ]; then #this is for modification of userID of an user + + read -p "Enter username that you wanted to modify it's user ID(UUID): " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldUserID=$(id -u "$usernameByUser") #extracting the existing userID using id command with -u it will return the userID of an user + echo "Existed userID for user $usernameByUser is: $oldUserID" + read -p "Enter new userID that you wanted to modify for user $usernameByUser: " newUserIdByUser #taking new userID input + sudo usermod -u "$newUserIdByUser" "$usernameByUser" #using -u option with usermod command to modify it's userID + echo "Successfully Updated the userID for user $usernameByUser from $oldUserID to $newUserIdByUser ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user ID !" + fi + + +elif [ "$userOption" == "-mh" ] || [ "$userOption" == "--modhome" ]; then #this is for modification of default home directory of an user + + read -p "Enter username that you wanted to modify it's default home directory: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldHomeDirectory=$(grep "^$usernameByUser" /etc/passwd | awk -F: '{print $6}') ##extracting the existing home directory with the help of + #grep to search the username in the /etc/passwd file and + #pass the output to awk command and given -F: for splitting + #with semicolon and using print with $6 6th argument to throw + #the default home directory as an output and assigning to varaible. + + echo "Default user home directory for user $usernameByUser is: $oldHomeDirectory" + read -p "Enter new user home directory that you wanted to modify for user $usernameByUser: " newUserHomeDirByUser + sudo usermod -d "$newUserHomeDirByUser" -m "$usernameByUser" # using -d option with usermod command to modify the default home directory. + #-m: moving all the files there in old directory to new directory. + echo "Successfully Updated the home directory for user $usernameByUser from $oldHomeDirectory to $newUserHomeDirByUser ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user default home directory !" + fi + + +elif [ "$userOption" == "-ms" ] || [ "$userOption" == "--modshell" ]; then ##this is for modification of default shell of an user + + read -p "Enter username that you wanted to modify it's default shell: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldShell=$(grep "^$usernameByUser" /etc/passwd | awk -F: '{print $7}') #extracting the existing home directory with the help of + #grep to search the username in the /etc/passwd file and + #pass the output to awk command and given -F: for splitting + #with semicolon and using print with $7 7th argument to throw + #the default shell path as an output and assigning to varaible. + echo "Default Shell for user $usernameByUser is: $oldShell" + read -p "Enter new shell path that you wanted to modify for user $usernameByUser: " newShell + sudo usermod -s "$newShell" "$usernameByUser" + echo "Successfully Updated the new Shell for user $usernameByUser from $oldShell to $newShell ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user default shell !" + fi + + +elif [ "$userOption" == "-mg" ] || [ "$userOption" == "--modgroup" ]; then ##this is for modification user group of an user + + read -p "Enter username that you wanted to modify it's group: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldGroup=$(id -gn $usernameByUser) #-g: Display the numeric group ID (GID) of the user. + #-n: Display the name of the user or group. + # using -gn, combines both options, and the command will display the name of the primary group associated with the user. + echo "Existed group name for user $usernameByUser is: $oldGroup" + read -p "Enter group name that you wanted to modify for user $usernameByUser: " newGroup + + if grep -q "^$newGroup:" /etc/group; then #checking if provided group name is exists or not in /etc/group file and add the username to group. + sudo usermod -aG $newGroup $usernameByUser #using -aG option with usermod command to add the specified group to the user. + #-a: This option tells the usermod command to append the user to the specified group(s) without r removing them from any other groups. + #-G: This option specifies the list of supplementary groups to which the user should be added. Mu ltiple group names can be provided, separated by commas, to add the user to multiple groups at once. + echo "Successfully Updated the new group for user $usernameByUser from $oldGroup to $newGroup ! " + else + echo "mentioned group is not present in system , please provided the existed group name !" + fi + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's group name !" + fi + + +elif [ "$userOption" == "-mpa" ] || [ "$userOption" == "--modpassage" ]; then #this is for modification of password expiration date for user account. + + read -p "Enter username that you wanted to add a account password expiration date: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + read -p "Enter how many number of days password will expire for user $usernameByUser: " passExpireDays #taking password expiry in days as a input + passwd -x "$passExpireDays" "$usernameByUser" #The passwd command is used to set or change a user's password in Linux + #The -x option is used to set the maximum number of days a password can be used before it expires. + + echo "Successfully Updated the password expiry for user $usernameByUser ! " + echo + echo "Now the password expiry date information as follows..." + chage -l $usernameByUser #The chage command in Linux is used to manage user password aging information. It allows you to view and modify passwor d expiration. + #The -l option is used with the chage command to display the password aging information for a user account + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's password expiry !" + fi + + +elif [ "$userOption" == "-mas" ] || [ "$userOption" == "--modaccstatus" ]; then #this is for locking/unlocking the user account. + + read -p "Enter username that you wanted to Lock/Unlock: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + echo "Enter your choice 1 or 2: " + echo "choose 1 to Lock the user account" + echo "choose 2 to unlock the user account" + read accountStatusByUser + if [ $accountStatusByUser == 1 ]; then + usermod -L $usernameByUser #-L option is to lock the useraccount with usermod command. + echo "user account $usernameByUser is locked successfully !" + elif [ $accountStatusByUser == 2 ]; then + usermod -U $usernameByUser #-U option is to unlock the useraccount with usermod command. + echo "user account $usernameByUser is unlocked successfully !" + else + echo "Please enter the valid option !" + + #To view the user account status whether it is locked or not we can use: passwd -S "$username" + fi + else + echo "user $usernameByUser is not existed, so please choose an existed user to Lock/Unlock !" + fi + +else #if user enters any different option prompting the user to provide correct option. + echo "Invalid option, Please enter the correct user option!" +fi + + + diff --git a/Self-solutions/Day_3/day3_solution_practice.sh b/Self-solutions/Day_3/day3_solution_practice.sh new file mode 100644 index 0000000..76b2aea --- /dev/null +++ b/Self-solutions/Day_3/day3_solution_practice.sh @@ -0,0 +1,837 @@ +#!/bin/bash +#set -x + +##################################################################### +# Script Name: day_3_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 2, 2023 +# Description: This script contains solution for Day 3 User Account Management as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day_3__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +######################################## Day-3 Challenge: User Account Management ######################################### + +#In this challenge, you will create a bash script that provides options for managing user accounts on the system. The script should allow users to perform various user account-related tasks based on command-line arguments. + +###########Part 1: Account Creation +#Implement an option -c or --create that allows the script to create a new user account. The script should prompt the user to enter the new username and password. + +#Ensure that the script checks whether the username is available before creating the account. If the username already exists, display an appropriate message and exit gracefully. + +#After creating the account, display a success message with the newly created username. + + +#########Part 2: Account Deletion +#Implement an option -d or --delete that allows the script to delete an existing user account. The script should prompt the user to enter the username of the account to be deleted. + +#Ensure that the script checks whether the username exists before attempting to delete the account. If the username does not exist, display an appropriate message and exit gracefully. + +#After successfully deleting the account, display a confirmation message with the deleted username. + + +#########Part 3: Password Reset +#Implement an option -r or --reset that allows the script to reset the password of an existing user account. The script should prompt the user to enter the username and the new password. + +#Ensure that the script checks whether the username exists before attempting to reset the password. If the username does not exist, display an appropriate message and exit gracefully. + +#After resetting the password, display a success message with the username and the updated password. + + +########Part 4: List User Accounts +#Implement an option -l or --list that allows the script to list all user accounts on the system. The script should display the usernames and their corresponding user IDs (UID). + + +#######Part 5: Help and Usage Information +#Implement an option -h or --help that displays usage information and the available command-line options for the script. + + +#######Bonus Points (Optional) +#If you want to challenge yourself further, you can add additional features to the script, such as: + +#Displaying more detailed information about user accounts (e.g., home directory, shell, etc.). +#Allowing the modification of user account properties (e.g., username, user ID, etc.). +#Remember to handle errors gracefully, provide appropriate user prompts, and add comments to explain the logic and purpose of each part of the script. + +#Created function to list out the User Options to run the script. +displayUserOptions() { + +echo +echo "Usage: ./day3_challenge_solution.py [OPTIONS]" +echo "Options:" +echo " -c, --create Create a new user account" +echo " -d, --delete Delete an existing user account" +echo " -r, --reset Reset password for an existing user account" +echo " -l, --list List all user accounts on the system" +echo " -h, --help Display this help and exit." +echo +echo "For Bonus features please use below options" +echo " -ui, --userinfo Display more information about an existed user account" +echo " -mu, --modusername Modify username for an existing user account" +echo " -muid, --moduserid Modify user ID for an existing user account" +echo " -mh, --modhome Modify home directory for an existing user account " +echo " -ms, --modshell Modify default shell for an existing user account" +echo +echo "############## Below options are for the future implementation ##############################" +echo " -mg, --modgroup Modify group for an existing user account " +echo " -mpa, --modpassage Modify password expiration date for an existing user account" +echo " -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account" +echo + +} + +#Created the function to check if user is already existed or not in our system. +is_user_exists() { + userName=$1 #we are taking function argument that passess while calling the function. here $1 is for user provided username input. + + if grep -q "^$userName:" /etc/passwd; then #checking if user already present or not using + #grep command checks if the specifie username that starts with $username is present in /etc/passwd output or #not + #-q option with grep will hide the output of the grep command + + return 0 #returning 0 if username is present otherwise sending 1. + else + return 1 + fi + +} + +displayUserOptions #calling this function to dispay the user option at the time of script runs. + +userOption=$1 #taking the command line 1st argument that pass while running the script and assigning to this variable. + +if [ "$userOption" == "-c" ] || [ "$userOption" == "--create" ]; then #putting two conditions to check -c OR --create user option to create the user. + + + read -p "Enter username to create the user account: " usernameByUser #taking username input from the user to create the user + is_user_exists "$usernameByUser" #passing the user provided username to the is_user_exists function as a command line argument. + + if [ $? -eq 0 ]; then #here $? - checks the previous command output and get the output here and i am comparing it with 0 means user exists. + echo "user $usernameByUser already existed, so please create the user with different username!" + exit 0 #existing from the script with safe command exit 0 with successful run if user exists. + fi + read -p "Enter password to create the account: " passwordByUser + sudo useradd "$usernameByUser" #using useradd command with sudo permission to create the user + echo "$usernameByUser:$passwordByUser" | chpasswd #assigning the user provided password to created user using echo to pass the output to chpasswd. + echo "user account $usernameByUser has been created successfully!" + +elif [ "$userOption" == "-d" ] || [ "$userOption" == "--delete" ]; then + read -p "Enter username to delete the user account: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + sudo userdel "$usernameByUser" #deleting the user if user is present in our system. + echo "user account $usernameByUser has been deleted successfully!" + else + echo "user $usernameByUser is not existed, so please choose a existed user to delete!" + + fi +elif [ "$userOption" == "-r" ] || [ "$userOption" == "--reset" ]; then + read -p "Enter username to reset the user account password: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + echo "please enter a new password for $usernameByUser: " + read -s newUserPasswordByUser #read with -s option is to take the password by hiding the password to user while he enters. + echo "$usernameByUser:$newUserPasswordByUser" | chpasswd #same as assiging the password but also can useful to reset the new password. + echo "user account $usernameByUser reset password has completed successfully!" + else + echo "user $usernameByUser is not existed, so please choose a existed user to reset the password!" + + fi + +elif [ "$userOption" == "-l" ] || [ "$userOption" == "--list" ]; then + + echo "Username UID GID" #printing the username UID(User ID) and GID(group ID) + echo "---------------------" + while IFS=: read -r username _ uid gid _; do #here IFS is a field seperator which seperates the all the lines output of /etc/passwd with : semicolon + echo "$username $uid $gid" # that's why I have put = and : with IFS means IFS=: and after seperating with semicolon i have read the + done < /etc/passwd #username with $1 first argument , assigning $2 argument with dummy variable as we don't need this for now + #$2 argument is password basically and $3 and $4 arguments are UID and GID and leaving remaining arguments + #with _ dummy variable till end and we are iterating till last line so using while loop to iterate and + #/etc/passwd contains all the usernames with details. + + + #we can also implement this with other approach as below + # Using awk to print the username (first field) and UID (third field) + #awk -F: '{print "Username:", $1, "UID:", $3}' /etc/passwd + #here we use awk with print to display the output to terminal +elif [ "$userOption" == "-h" ] || [ "$userOption" == "--help" ]; then + displayUserOptions #displaying the user options for help option. + + +#From here is for the bonus learning +elif [ "$userOption" == "-ui" ] || [ "$userOption" == "--userinfo" ]; then + + read -p "Enter username to know more information about the user account: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + sudo grep "$usernameByUser" /etc/passwd | awk -F: '{print "\n Username: ", $1"\n", "UID:", $3"\n", "Home directory:", $6"\n", "Default shell:", $7"\n"}' + #the above command will print out the Username, UID, Home directory, Default shell details for specific user. + #here we are using grep to find the username in the /etc/passwd file this will return whole line of output with : semicolon + #passing the output via | pipe symbol to awk command and here we are splitting line of output with : semicolon using F: + #using print to display the output to the terminal + else + echo "user $usernameByUser is not existed, so please choose an existed user to display more information about the user!" + + fi + + +elif [ "$userOption" == "-mu" ] || [ "$userOption" == "--modusername" ]; then #this is for modification of username + + read -p "Enter username that you wanted to modify it's username: " oldUsernameByUser + + is_user_exists "$oldUsernameByUser" + + if [ $? -eq 0 ]; then + read -p "Enter new username that you wanted to modify for user $oldUsernameByUser: " newUsernameByUser #taking new username as a input + sudo usermod -l "$newUsernameByUser" "$oldUsernameByUser" #using -l option with usermod to change the username + echo "Successfully Updated the username from $oldUsernameByUser to $newUsernameByUser! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's username!" + fi + + +elif [ "$userOption" == "-muid" ] || [ "$userOption" == "--moduserid" ]; then #this is for modification of userID of an user + + read -p "Enter username that you wanted to modify it's user ID(UUID): " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldUserID=$(id -u "$usernameByUser") #extracting the existing userID using id command with -u it will return the userID of an user + echo "Existed userID for user $usernameByUser is: $oldUserID" + read -p "Enter new userID that you wanted to modify for user $usernameByUser: " newUserIdByUser #taking new userID input + sudo usermod -u "$newUserIdByUser" "$usernameByUser" #using -u option with usermod command to modify it's userID + echo "Successfully Updated the userID for user $usernameByUser from $oldUserID to $newUserIdByUser ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user ID !" + fi + + +elif [ "$userOption" == "-mh" ] || [ "$userOption" == "--modhome" ]; then #this is for modification of default home directory of an user + + read -p "Enter username that you wanted to modify it's default home directory: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldHomeDirectory=$(grep "^$usernameByUser" /etc/passwd | awk -F: '{print $6}') ##extracting the existing home directory with the help of + #grep to search the username in the /etc/passwd file and + #pass the output to awk command and given -F: for splitting + #with semicolon and using print with $6 6th argument to throw + #the default home directory as an output and assigning to varaible. + + echo "Default user home directory for user $usernameByUser is: $oldHomeDirectory" + read -p "Enter new user home directory that you wanted to modify for user $usernameByUser: " newUserHomeDirByUser + sudo usermod -d "$newUserHomeDirByUser" "$usernameByUser" # using -d option with usermod command to modify the default home directory. + echo "Successfully Updated the home directory for user $usernameByUser from $oldHomeDirectory to $newUserHomeDirByUser ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user default home directory !" + fi + + +elif [ "$userOption" == "-ms" ] || [ "$userOption" == "--modshell" ]; then ##this is for modification of default shell of an user + + read -p "Enter username that you wanted to modify it's default shell: " usernameByUser + + is_user_exists "$usernameByUser" + + if [ $? -eq 0 ]; then + oldShell=$(grep "^$usernameByUser" /etc/passwd | awk -F: '{print $7}') #extracting the existing home directory with the help of + #grep to search the username in the /etc/passwd file and + #pass the output to awk command and given -F: for splitting + #with semicolon and using print with $7 7th argument to throw + #the default shell path as an output and assigning to varaible. + echo "Default Shell for user $usernameByUser is: $oldShell" + read -p "Enter new shell path that you wanted to modify for user $usernameByUser: " newShell + sudo usermod -s "$newShell" "$usernameByUser" + echo "Successfully Updated the new Shel for user $usernameByUser from $oldShell to $newShell ! " + else + echo "user $usernameByUser is not existed, so please choose an existed user to modify it's user default shell !" + fi + + + +else #if user enters any different option prompting the user to provide correct option. + echo "Invalid option, Please enter the correct user option!" +fi + +##############################################Future implementation plan for more user modification############################### +#pla-1 +#input the group name(s) and add the user to the group. +#usermod -G sudo,ftp username + +#plan-2 +#input the date as same as format(2023-12-31) to set password expiration prefereably 90days and it will automatically send warning before expring the password in 7days using -w 7 as below. +#usermod -e 2023-12-31 -w 7 username + +#plan-3 +#take input option to (lock use -L) and (-U for unlock) the user account +#usermod -L username + +################################################################################################################### + + + + +#########################practice################# + +#practice-1 +sudo useradd username +sudo passwd username + + +#practice-2 +#practicing to provide a customized home directory, shell, or other settings for a user while creating or after creating the user, +#To specify a custom home directory, use the -d or --home option: +sudo useradd -d /path/to/custom_home_dir username +#To set a custom default shell, use the -s or --shell option: +sudo useradd -s /path/to/custom_shell username +#After Creating the User: +#If you have already created the user and want to modify their settings, with various options: +#To change the user's home directory, use the -d or --home option: +sudo usermod -d /path/to/custom_home_dir username +#To change the user's default shell, use the -s or --shell option: +sudo usermod -s /path/to/custom_shell username +#Provide Custom Configuration Files: +#can also provide custom configuration files for the user in their home directory. For example, you can create a .bashrc file in the user's home directory to customize their bash shell behavior. + + +#practice-3 +#practicing to view various user account details in a Unix-like operating system using different commands. +#id: This command displays user and group information for the current user or a specified user. +id # Display information for the current user +id username # Display information for the specified username + +whoami: #This command prints the username of the current user. + +finger: #The finger command provides information about a user's login name, real name, terminal, login time, idle time, and more. but we need to install this tool before use. + +cat /etc/passwd: #This command shows the user account details stored in the /etc/passwd file, including the username, user ID (UID), group ID (GID), home directory, and default shell. + +getent passwd: #This command retrieves user account details from the system database. + +grep: #You can use grep to filter specific user details from /etc/passwd or other files. + +grep username /etc/passwd # Display details for the specified username +cat /etc/passwd | grep shell # Display users with a specific shell + +ls -l /home: #This command shows the list of user home directories and their permissions. + +cat /etc/shells: #This command displays the available shells on the system. + + + +#practice-4 +#practicing logical AND (&&) and logical OR (||) operators to perform conditional operations based on the success or failure of commands. These operators allow you to chain multiple commands together and control the flow of execution. + +#Logical AND (&&): +#The && operator is used to execute the next command only if the previous command succeeds (returns an exit status of 0). +ls /path/to/directory && echo "Directory listing successful" + +#Logical OR (||): +#The || operator is used to execute the next command only if the previous command fails (returns a non-zero exit status). +rm /path/to/file || echo "File not found" +#command1 && command2 || command3 + + +#use the logical AND (&&) and logical OR (||) operators within an if statement to perform conditional checks based on the success or failure of commands. +if command1 && command2 +then + # Code block to execute if both command1 and command2 succeed +elif command3 || command4 +then + # Code block to execute if command3 succeeds or command4 fails +else + # Code block to execute if all commands fail +fi + +if ls /path/to/directory && grep "pattern" /path/to/file +then + echo "Both commands succeeded." +elif grep "pattern1" /path/to/file || grep "pattern2" /path/to/file +then + echo "At least one of the grep commands succeeded." +else + echo "Both commands failed." +fi + +#!/bin/bash + +file="example.txt" + +# Check if the file exists and is readable +if [ -r "$file" ] && [ -f "$file" ] +then + echo "The file exists and is readable." +else + echo "The file does not exist or is not readable." +fi + + +#practice-5 +# find out if specific user present or not before deleting the user in shell scripting +#!/bin/bash + +# Replace "username" with the username you want to check +username="testuser" + +# Check if the user exists using the getent command and grep +if getent passwd | grep -q "^$username:"; then + echo "User $username exists. Deleting the user..." + + # Add your code here to delete the user, e.g., using the userdel command + # For example: + # userdel "$username" + + echo "User $username has been deleted." +else + echo "User $username does not exist." +fi + + + +#practice-6 +#Using grep to search for the user in /etc/passwd file: +username="someuser" + +if grep -q "^$username:" /etc/passwd; then + echo "User $username exists." +else + echo "User $username does not exist." +fi + + +#practice-7 +#practicing functions +# Function definition with arguments +add_numbers() { + num1=$1 + num2=$2 + sum=$((num1 + num2)) + echo "The sum of $num1 and $num2 is: $sum" +} + +# Function call with arguments +add_numbers 10 20 + +#exaple2 +# Function definition with arguments +add_numbers() { + num1=$1 + num2=$2 + sum=$((num1 + num2)) + + # Set the sum as the exit status + exit $sum +} + +# Function call with arguments +add_numbers 10 20 + +# Access the exit status and print the result +result=$? +echo "The sum is: $result" + +#note: we cannot return the non-integer values from function + +#example3 +# Function definition to check if a number is even +is_even() { + num=$1 + if (( num % 2 == 0 )); then + return 0 # Exit status 0 means the number is even + else + return 1 # Exit status 1 means the number is not even + fi +} + +# Function call within an if statement +number=10 +if is_even "$number"; then + echo "$number is even." +else + echo "$number is not even." +fi + + + +#for safe exit use exit 0 +#exit [status] +#status: The exit status that will be returned to the calling process. By convention, an exit status of 0 indicates success, and any non-zero value indicates an error or failure. +#!/bin/bash + +# Your script commands here... + +# Some error occurred, exit the script with a non-zero status +exit 1 + + + + +#practice-8 +#practicing To reset the password for a user in a shell script, you can use the passwd command along with some echo statements to provide the new password. +#!/bin/bash + +# Function to reset password for a user +reset_password() { + local username="$1" + + # Check if the user exists + if id "$username" &>/dev/null; then + echo "Resetting password for user: $username" + echo "Enter the new password for $username:" + read -s new_password + echo "$username:$new_password" | chpasswd + echo "Password reset successfully." + else + echo "User $username does not exist." + fi +} + +# Call the function and pass the username as an argument +reset_password "your_username" + + + + + +#practice-9 +#To display all the usernames and their associated user IDs (UIDs) and group IDs (GIDs) in a shell script, you can use the cut command along with the /etc/passwd file. The /etc/passwd file contains information about all the users on the system +#!/bin/bash + +# Function to display all user information +display_all_users_info() { + echo "Username UID GID" + echo "---------------------" + while IFS=: read -r username _ uid gid _; do + echo "$username $uid $gid" + done < /etc/passwd +} + +# Call the function to display all user information +display_all_users_info + +#The -r option with the read command is used to prevent backslashes \ from being interpreted as escape characters. When reading input from a file, using the -r option ensures that backslashes are treated as regular characters and not escape characters. + +#how IFS=: works and each its = and ; +# shell scripting, IFS stands for "Internal Field Separator." It is a special environment variable that defines the delimiter used to split a line of text into fields when using commands like read or for loops. + +#By default, the value of IFS is set to whitespace characters (space, tab, and newline). However, you can change its value to a different character or a string of characters to split input lines based on that specific separator. + +#In the example you provided, IFS=:, the = sign is used to set the value of IFS, and : is the delimiter that will be used to split the input lines into fields. + +#while IFS=: read -r username _ _ uid _; do: This is a while loop that reads each line from the users.txt file, splits it into fields using : as the delimiter (because of the IFS=: setting), and assigns those fields to the variables username, uid, and two dummy variables _. The dummy variables _ are used to skip the other fields that are not needed. + +#practice-10 +#to display all the username and its IDs in shell script with awk -F: optin +#!/bin/bash + +# Assuming the user data is stored in a file called users.txt +# The format is: username:password:UID:GID:gecos:home:shell + +# Using awk to print the username (first field) and UID (third field) +awk -F: '{print "Username:", $1, "UID:", $3}' users.txt +#we use awk with the -F option to specify that the field separator is : (colon). Then, we use $1 and $3 to refer to the first and third fields, respectively, which correspond to the username and UID in each line of the users.txt file. +#The print statement in awk is used to print text or data to the output. + +#practice-11 +#function that takes a string as a parameter +#!/bin/bash + +# Define a function that takes a string as a parameter +print_string() { + local input_string=$1 + echo "The input string is: $input_string" +} + +# Call the function and pass a string as an argument +my_string="Hello, this is a sample string." +print_string "$my_string" + + +#practice-12 +#function with passing the string and storing the return value and using in if statement +#!/bin/bash + +# Define a function that takes a string as a parameter +check_string() { + local input_string=$1 + + # Check if the string is empty + if [ -z "$input_string" ]; then + return 1 + else + return 0 + fi +} + +# Call the function and pass a string as an argument +my_string="Hello, this is a sample string." +check_string "$my_string" + +# Check the return value of the function in the if statement +if [ $? -eq 0 ]; then + echo "The string is not empty." +else + echo "The string is empty." +fi + + +#practice-13 +#o add a new user and set a password in a shell script, you can use the useradd and passwd commands. +#!/bin/bash + +# Function to add a new user and set the password +add_user_with_password() { + local username=$1 + local password=$2 + + # Check if the user already exists + if id "$username" &>/dev/null; then + echo "User '$username' already exists." + else + # Add the new user + useradd "$username" + + # Set the password for the new user + echo "$username:$password" | chpasswd + + echo "User '$username' added with the provided password." + fi +} + +# Call the function and pass the username and password as arguments +new_username="newuser" +new_password="mypassword" +add_user_with_password "$new_username" "$new_password" + + +#practice-14 +#To add a new user and set a password in a shell script, you can use the useradd and passwd commands. +#!/bin/bash + +# Define the username and password +new_username="newuser" +new_password="mypassword" + +# Check if the user already exists +if id "$new_username" &>/dev/null; then + echo "User '$new_username' already exists." +else + # Add the new user + useradd "$new_username" + + # Set the password for the new user + echo "$new_username:$new_password" | chpasswd + + echo "User '$new_username' added with the provided password." +fi + + +#practice-15 +#To modify user account details like UID, username, and home directory in a shell script, you can use the usermod command. +#!/bin/bash + +# Define the old and new usernames +old_username="olduser" +new_username="newuser" + +# Define the new UID +new_uid="1001" + +# Define the new home directory +new_home="/path/to/new/home/directory" + +# Check if the old user exists +if id "$old_username" &>/dev/null; then + # Modify the username + if [ "$old_username" != "$new_username" ]; then + usermod -l "$new_username" "$old_username" + fi + + # Modify the UID + if [ "$(id -u "$old_username")" != "$new_uid" ]; then + usermod -u "$new_uid" "$new_username" + fi + + # Modify the home directory + if [ "$(eval echo ~$old_username)" != "$new_home" ]; then + usermod -d "$new_home" -m "$new_username" + fi + + echo "User details modified successfully." +else + echo "User '$old_username' does not exist." +fi + + + + + +#more modifications for an existed user +#n addition to modifying the username, UID, and home directory, the usermod command can be used to modify various other attributes of a user account. Some common attributes that can be modified with usermod include: + +#Shell: You can change the default shell for the user using the -s option. For example, to change the shell to /bin/bash, use usermod -s /bin/bash username. + +#User's groups: You can add or remove the user from specific groups using the -G option. For example, to add the user to the sudo and ftp groups, use usermod -G sudo,ftp username. + +#Account expiration date: You can set an expiration date for the user account using the -e option. For example, to set the account to expire on a specific date, use usermod -e YYYY-MM-DD username. + +#Account status: You can lock or unlock the user account using the -L (lock) and -U (unlock) options, respectively. For example, to lock the account, use usermod -L username. + +#Password aging: You can modify password aging settings like password expiration and warning days using the -e and -w options. For example, to set the password to expire after 90 days and provide a 7-day warning, use usermod -e 2023-12-31 -w 7 username. + +#User's full name or comment: You can change the user's full name or add a comment using the -c option. For example, to set the full name to "John Doe" and add a comment "DevOps Engineer", use usermod -c "John Doe, DevOps Engineer" username. + +#Disable login: To disable login for a user, you can use the -s /sbin/nologin option. This will prevent the user from logging in with a shell. + + +#note +## Modify the home directory + if [ "$(eval echo ~$old_username)" != "$new_home" ]; then + usermod -d "$new_home" -m "$new_username" + fi + +#what is -d and -m here +#-d: This option is used to change the user's home directory. When -d is followed by a directory path, it will set the new home directory for the user account. + +#-m: This option is used to move the contents of the user's old home directory to the new home directory. It is typically used in conjunction with the -d option to move the home directory when changing the user's home directory. + + +#practice-16 +#get the UID of a user by their username: +#!/bin/bash + +username="your_username_here" + +# Get the UID using the 'id' command +user_id=$(id -u "$username") + +# Print the UID +echo "User ID for $username: $user_id" + + +#practice-17 +#To find out the primary group of a user in shell scripting, +#use the id command along with the -gn option. +#!/bin/bash + +# Replace 'username' with the actual username you want to check +username="username" + +# Get the primary group name of the user +group_name=$(id -gn $username) + +echo "The primary group of $username is: $group_name" +#In the id command, the -gn option is used to display the group name of a user. +#-g: Display the numeric group ID (GID) of the user. +#-n: Display the name of the user or group. + + +#practice-18 +#To check if a group exists before adding a user to it in shell scripting, +#use the grep command to search for the group in the /etc/group file. +#!/bin/bash + +group_name="developers" +user_name="john" + +# Check if the group exists +if grep -q "^$group_name:" /etc/group; then + echo "Group $group_name exists." + # Add the user to the group + usermod -aG "$group_name" "$user_name" + echo "User $user_name added to group $group_name." +else + echo "Group $group_name does not exist." +fi +#In the shell script provided above, the -aG options are used with the usermod command to add a user to a group +#a: This option tells the usermod command to append the user to the specified group(s) without removing them from any other groups. +#-G: This option specifies the list of supplementary groups to which the user should be added. Multiple group names can be provided, separated by commas, to add the user to multiple groups at once. +#In the script, the line usermod -aG "$group_name" "$user_name" is used to add the user specified by $user_name to the group specified by $group_name without affecting their membership in any other groups. + + +#practice-19 +#To check the expiration date of a user account password in shell scripting, +#use the chage command with the -l option. The chage command is used to change user password expiry information, and the -l option displays the current password expiry details for the user. +#!/bin/bash + +# Provide the username whose password expiry information you want to check +username="your_username" + +# Get the password expiry information using chage -l command +password_expiry_info=$(chage -l "$username" 2>/dev/null) + +# Check if the password expiry information is available +if [ -n "$password_expiry_info" ]; then + echo "Password Expiry Information for User: $username" + echo "$password_expiry_info" +else + echo "User $username does not exist or password expiry information is not available." +fi + +#practice-20 +#checking command to set the password expiration for a user: +passwd -x +#ex:passwd -x 30 john +#The passwd command is used to set or change a user's password in Linux. The -x option is used to set the maximum number of days a password can be used before it expires. +#When you run the passwd command with the -x option and a number (e.g., passwd -x 30 john), it means that you are setting the password expiration policy for the user "john" to 30 days. This means that after 30 days, the user "john" will be required to change their password. + + + +#practice-21 +#To display the password expiration date for a user account in Linux, +# use the chage command. The chage command allows you to view and modify the password aging information for a user. To see the password expiration date, +chage -l username +#The chage command in Linux is used to manage user password aging information. It allows you to view and modify password expiration and other related settings for user accounts. When you run the chage command without any options, it displays the current password aging information for the specified user. +#The -l option is used with the chage command to display the password aging information for a user account. + +#When you run chage -l username, it shows the following information for the specified user: +#Last password change date: This is the date when the user's password was last changed. + +#Password expiration date: This is the date when the user's password will expire, and the user will be required to change it. + +#Minimum password age: This is the minimum number of days a password must be used before it can be changed again. + +#Maximum password age: This is the maximum number of days a password can be used before it expires. + +#Password inactive days: This is the number of days after the password has expired before the account is locked. + +#Account expiration date: This is the date when the user account will expire, and the user will no longer be able to log in. + +#Account inactive days: This is the number of days after the account has expired before it is permanently disabled. + +#By using the chage -l command, you can check the password aging settings for a user account and ensure that password policies are properly configured for security purposes. + + + +#practice-22 +#practicing to check if a user account is locked or not in shell scripting by using the passwd command along with the -S option. The passwd -S username command will display the status of the user account, including whether it is locked or not. +#!/bin/bash + +# Replace "username" with the actual username you want to check +username="username" + +# Use passwd -S to check the status of the user account +status=$(passwd -S "$username" | awk '{print $2}') + +# Check if the account is locked +if [ "$status" = "L" ]; then + echo "The account $username is locked." +else + echo "The account $username is not locked." +fi +# use the passwd -S command to get the status of the user account +#The status code "L" indicates that the account is locked, and "P" indicates that the account is active and not locked. + + + + + diff --git a/Self-solutions/Day_3/readme.txt b/Self-solutions/Day_3/readme.txt new file mode 100644 index 0000000..7c346e8 --- /dev/null +++ b/Self-solutions/Day_3/readme.txt @@ -0,0 +1,649 @@ +please run 'day3_challange_solution.sh' + + +sample output for the script day3_challange_solution.sh: + + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Invalid option, Please enter the correct user option! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --create + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to create the user account: user6 +Enter password to create the account: user6 +user account user6 has been created successfully! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --create + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to create the user account: user6 +user user6 already existed, so please create the user with different username! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --reset + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to reset the user account password: user6 +please enter a new password for user6: +user account user6 reset password has completed successfully! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --list + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Username UID GID +--------------------- +root 0 0 +daemon 1 1 +bin 2 2 +sys 3 3 +sync 4 65534 +games 5 60 +man 6 12 +lp 7 7 +mail 8 8 +news 9 9 +uucp 10 10 +proxy 13 13 +www-data 33 33 +backup 34 34 +list 38 38 +irc 39 39 +gnats 41 41 +nobody 65534 65534 +systemd-network 100 102 +systemd-resolve 101 103 +messagebus 102 105 +systemd-timesync 103 106 +syslog 104 111 +_apt 105 65534 +tss 106 112 +uuidd 107 113 +tcpdump 108 114 +sshd 109 65534 +pollinate 110 1 +landscape 111 116 +fwupd-refresh 112 117 +ec2-instance-connect 113 65534 +_chrony 114 121 +ubuntu 1000 1000 +lxd 999 100 +devops 1001 1001 user1 1002 1002 +user2 1009 1003 +user3 1010 1010 +user44 1022 1011 +user6 1023 1023 + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --delete + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to delete the user account: user6 +user account user6 has been deleted successfully! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --delete + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to delete the user account: user6 +user user6 is not existed, so please choose a existed user to delete! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --help + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh -c + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to create the user account: user7 +Enter password to create the account: user7 +user account user7 has been created successfully! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user7 + + Username: user7 + UID: 1024 + Home directory: /home/user7 + Default shell: /bin/sh + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modusername + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to modify it's username: user7 +Enter new username that you wanted to modify for user user7: user77 +Successfully Updated the username from user7 to user77! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user7 +user user7 is not existed, so please choose an existed user to display more information about the user! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user77 + + Username: user77 + UID: 1024 + Home directory: /home/user7 + Default shell: /bin/sh + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --moduserid + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to modify it's user ID(UUID): user77 +Existed userID for user user77 is: 1024 +Enter new userID that you wanted to modify for user user77: 1025 +Successfully Updated the userID for user user77 from 1024 to 1025 ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user77 + + Username: user77 + UID: 1025 + Home directory: /home/user7 + Default shell: /bin/sh + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modhome + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to modify it's default home directory: user77 +Default user home directory for user user77 is: /home/user7 +Enter new user home directory that you wanted to modify for user user77: /home/user77 +Successfully Updated the home directory for user user77 from /home/user7 to /home/user77 ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user77 + + Username: user77 + UID: 1025 + Home directory: /home/user77 + Default shell: /bin/sh + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modshell + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to modify it's default shell: user77 +Default Shell for user user77 is: /bin/sh +Enter new shell path that you wanted to modify for user user77: /bin/bash +Successfully Updated the new Shell for user user77 from /bin/sh to /bin/bash ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --userinfo + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username to know more information about the user account: user77 + + Username: user77 + UID: 1025 + Home directory: /home/user77 + Default shell: /bin/bash + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modgroup + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to modify it's group: user77 +Existed group name for user user77 is: user7 +Enter group name that you wanted to modify for user user77: user4 +Successfully Updated the new group for user user77 from user7 to user4 ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modpassage + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to add a account password expiration date: user77 +Enter how many number of days password will expire for user user77: 120 +passwd: password expiry information changed. +Successfully Updated the password expiry for user user77 ! + +Now the password expiry date information as follows... +Last password change : Aug 02, 2023 +Password expires : Nov 30, 2023 +Password inactive : never +Account expires : never +Minimum number of days between password change : 0 +Maximum number of days between password change : 120 +Number of days of warning before password expires : 7 + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modaccstatus + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to Lock/Unlock: user77 +Enter your choice 1 or 2: +choose 1 to Lock the user account +choose 2 to unlock the user account +1 +user account user77 is locked successfully ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# passwd -S user77 +user77 L 08/02/2023 0 120 7 -1 + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# ./day3_challenge_solution.sh --modaccstatus + +Usage: ./day3_challenge_solution.py [OPTIONS] +Options: + -c, --create Create a new user account + -d, --delete Delete an existing user account + -r, --reset Reset password for an existing user account + -l, --list List all user accounts on the system + -h, --help Display this help and exit. + +For Bonus features please use below options + -ui, --userinfo Display more information about an existed user account + -mu, --modusername Modify username for an existing user account + -muid, --moduserid Modify user ID for an existing user account + -mh, --modhome Modify home directory for an existing user account + -ms, --modshell Modify default shell for an existing user account + -mg, --modgroup Modify group for an existing user account + -mpa, --modpassage Modify password expiration date for an existing user account + -mas, --modaccstatus Modfiy account status(Lock/Unlock) for an existing user account + +Enter username that you wanted to Lock/Unlock: user77 +Enter your choice 1 or 2: +choose 1 to Lock the user account +choose 2 to unlock the user account +2 +user account user77 is unlocked successfully ! + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_3# passwd -S user77 +user77 P 08/02/2023 0 120 7 -1 + + + diff --git a/Self-solutions/Day_4/Part1README.md b/Self-solutions/Day_4/Part1README.md new file mode 100644 index 0000000..3231f17 --- /dev/null +++ b/Self-solutions/Day_4/Part1README.md @@ -0,0 +1,83 @@ +please run "day4_part1_challlenge_solution.sh" + +sample output for the script day3_challange_solution.sh: + +``` +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# ./day4_part1_challenge_solution.sh nginx + +Mentioned process 'nginx' is running in the system !!! +● nginx.service - A high performance web server and a reverse proxy server + Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) + Active: active (running) since Thu 2023-08-03 13:37:51 UTC; 3min 22s ago + Docs: man:nginx(8) + Process: 46948 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Process: 46949 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Main PID: 46950 (nginx) + Tasks: 2 (limit: 1141) + Memory: 2.5M + CPU: 20ms + CGroup: /system.slice/nginx.service + ├─46950 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" + └─46952 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" + +Aug 03 13:37:51 ip-172-31-91-38 systemd[1]: Starting A high performance web server and a reverse proxy server... +Aug 03 13:37:51 ip-172-31-91-38 systemd[1]: Started A high performance web server and a reverse proxy server. + + + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# #stopping manually + + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# systemctl stop nginx + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# ./day4_part1_challenge_solution.sh nginx + +Mentioned process 'nginx' is not running in the system, Attempting to restart... + +Attempting restart to the process 'nginx' automatically ! +Attempt number: '1' +process 'nginx' is running successfully after restart attempt-'1' !!! + +● nginx.service - A high performance web server and a reverse proxy server + Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) + Active: active (running) since Thu 2023-08-03 13:44:00 UTC; 25ms ago + Docs: man:nginx(8) + Process: 47056 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Process: 47057 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Main PID: 47058 (nginx) + Tasks: 2 (limit: 1141) + Memory: 2.5M + CPU: 22ms + CGroup: /system.slice/nginx.service + ├─47058 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" + └─47060 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" + +Aug 03 13:44:00 ip-172-31-91-38 systemd[1]: Starting A high performance web server and a reverse proxy server... +Aug 03 13:44:00 ip-172-31-91-38 systemd[1]: Started A high performance web server and a reverse proxy server. + + + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# ./day4_part1_challenge_solution.sh dummy-nginx + +Mentioned process 'dummy-nginx' is not running in the system, Attempting to restart... + +Attempting restart to the process 'dummy-nginx' automatically ! +Attempt number: '1' +Failed to start dummy-nginx.service: Unit dummy-nginx.service not found. +Attempt number: '2' +Failed to start dummy-nginx.service: Unit dummy-nginx.service not found. +Attempt number: '3' +Failed to start dummy-nginx.service: Unit dummy-nginx.service not found. +After 3 attempts to restart we could not able to start the process 'dummy-nginx' please try manually ! + +Sending slack notification !!!!!!!!!!! + +ok +Slack notification sent successfully !!! +``` + +#After sending the slack notification below notification we can see. + +![slack-notification](https://github.com/salvathshaik/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/39498166/133e4dd7-fb64-44a5-a5b5-24b5808addeb) + + diff --git a/Self-solutions/Day_4/Part2README.md b/Self-solutions/Day_4/Part2README.md new file mode 100644 index 0000000..3a9935b --- /dev/null +++ b/Self-solutions/Day_4/Part2README.md @@ -0,0 +1,163 @@ +please run day4_part2_challenge_solution.sh file. + +sample output of this script as follows + +``` +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# ./day4_part2_challenge_solution.sh + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 1 +CPU Usage: 6.20% Mem Usage: 26.00% Disk Usage: 39%% + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 1 + +Showing metrics again in 5 seconds... please wait! + +CPU Usage: 0.00% Mem Usage: 26.00% Disk Usage: 39%% + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 2 +Enter the name of the service to monitor: nginx + +Mentioned process 'nginx' is running in the system !!! +● nginx.service - A high performance web server and a reverse proxy server + Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) + Active: active (running) since Thu 2023-08-03 13:44:00 UTC; 3h 19min ago + Docs: man:nginx(8) + Process: 47056 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Process: 47057 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Main PID: 47058 (nginx) + Tasks: 2 (limit: 1141) + Memory: 2.7M + CPU: 171ms + CGroup: /system.slice/nginx.service + ├─47058 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" + └─47060 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" + +Aug 03 13:44:00 ip-172-31-91-38 systemd[1]: Starting A high performance web server and a reverse proxy server... +Aug 03 13:44:00 ip-172-31-91-38 systemd[1]: Started A high performance web server and a reverse proxy server. + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 4 +Invalid option '4'. please try again wtih the availiable options. + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 3 + +Exiting .. + + +Stopping the nginx service manually to check this scenario + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# systemctl stop nginx + +root@ip-172-31-91-38:~/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4# ./day4_part2_challenge_solution.sh + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 2 +Enter the name of the service to monitor: nginx + +Mentioned service 'nginx' is not running in the system... + +Do you want to start nginx? (Y/N): Y +'nginx' service started successfully!! +● nginx.service - A high performance web server and a reverse proxy server + Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) + Active: active (running) since Thu 2023-08-03 17:07:11 UTC; 17ms ago + Docs: man:nginx(8) + Process: 48414 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Process: 48415 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) + Main PID: 48416 (nginx) + Tasks: 2 (limit: 1141) + Memory: 2.5M + CPU: 22ms + CGroup: /system.slice/nginx.service + ├─48416 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" + └─48418 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" + +Aug 03 17:07:11 ip-172-31-91-38 systemd[1]: Starting A high performance web server and a reverse proxy server... +Aug 03 17:07:11 ip-172-31-91-38 systemd[1]: Started A high performance web server and a reverse proxy server. + + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option: 2 +Enter the name of the service to monitor: dummy-nginx-service + +Mentioned service 'dummy-nginx-service' is not running in the system... + +Do you want to start dummy-nginx-service? (Y/N): Y +Failed to start dummy-nginx-service.service: Unit dummy-nginx-service.service not found. +Failed to start the service dummy-nginx-service. Please check the service name and try again!!! + +Main Menu + +------ Monitoring Metrics Script ------- + +Choose below options + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + +Enter your option:3 + +Exiting .. + +``` + diff --git a/Self-solutions/Day_4/day4_part1_challenge_solution.sh b/Self-solutions/Day_4/day4_part1_challenge_solution.sh new file mode 100755 index 0000000..2f91682 --- /dev/null +++ b/Self-solutions/Day_4/day4_part1_challenge_solution.sh @@ -0,0 +1,120 @@ +#!/bin/bash + +##################################################################### +# Script Name: day4_part1_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 3, 2023 +# Description: This script contains solution for Day 4 part-1 process monitoring and management as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day4_part1__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + + + +########################################### BashBlaze Scripting Challenge - Day 4 ####################################### +#Welcome to the Bash Scripting Challenge - Day 4! This challenge is designed to test your Bash scripting skills and problem-solving abilities in the context of process monitoring and management. + +############################################# Scenario ############### +#You are tasked with writing a Bash script that efficiently monitors a specific process on a Linux system. The script's primary goal is to ensure the process is always running, and if it unexpectedly stops, it should be restarted automatically. + +############################################ Task ############## +#1.Process Selection: +#The script should accept a command-line argument to specify the target process to monitor. For example: ./monitor_process.sh . + +#2.Process Existence Check: +#Implement a function that checks if the specified process is currently running on the system. +#If the process is running, print a message indicating its presence. + +#3.Restarting the Process: +#If the process is not running, implement a function that attempts to restart the process automatically. +#Print a message indicating the attempt to restart the process. +#Ensure the script does not enter an infinite loop while restarting the process. Limit the number of restart attempts. + +#4.Automation: +#Provide instructions on how to schedule the script to run at regular intervals using a cron job or any other appropriate scheduling method. + +#5.Documentation: +#Include clear and concise comments in the script to explain its logic and functionality. +#Write a separate document describing the purpose of the script, how to use it, and any specific considerations. + +#6.Bonus +#Implement a notification mechanism (e.g., email, Slack message) to alert administrators if the process requires manual intervention after a certain number of restart attempts. + +processNameByUser=$1 #taking first command line argument as a process name from user. + +check_if_process_running() { + + process_name=$1 + + if pgrep "$process_name" >/dev/null; then #checking if provided process is running or not + #The >/dev/null part in the shell script is used for redirecting the standard output of a command to the null dev -ice (/dev/null),which is a special device that discards any data written to it. + #If the process is running, pgrep will return a success status (exit code 0), and the output will be discarded. + # If the process is not running, pgrep will return a non-zero status, and the output will be discarded as well. + #The if statement checks the exit status, and based on that, it print the appropriate message without showing any output from the pgrep command itself. + return 0 + else + return 1 + fi +} + + +check_if_process_running "$processNameByUser" #passing the process name to the function + +if [ $? == 0 ]; then #comparing the output of above function usign $? with 0 means process is running. + echo + echo "Mentioned process '$processNameByUser' is running in the system !!!" + sudo systemctl status "$processNameByUser" #displaying the status of process. +else + echo + echo "Mentioned process '$processNameByUser' is not running in the system, Attempting to restart..." + echo + echo "Attempting restart to the process '$processNameByUser' automatically !" + + for ((restartAttempt=1; restartAttempt<=3; restartAttempt++)) #for loop to attempt for 3 times to restart the process + do + + echo "Attempt number: '$restartAttempt'" + + sudo systemctl start "$processNameByUser" #using systemctl command to start the service. + + + #checking if our restart attempt is succsfull or not. + check_if_process_running "$processNameByUser" + if [ $? == 0 ]; then + echo "process '$processNameByUser' is running successfully after restart attempt-'$restartAttempt' !!!" + echo + sudo systemctl status "$processNameByUser" #displaying the status of the process. + break #if success then we break the loop. + fi + + if [ $restartAttempt == 3 ]; then #after 3 attempts also if not restarted showing message. + echo "After 3 attempts to restart we could not able to start the process '$processNameByUser' please try manually !" + echo + echo "Sending slack notification !!!!!!!!!!!" + echo + SLACK_WEBHOOK_URL="https://hooks.slack.com/services/place-your-webhook-url" + SLACK_CHANNEL="#shell-scripting-projects" + SLACK_USERNAME="Process Monitor" + SLACK_ICON_EMOJI=":warning:" + MESSAGE=":warning: Process '$processNameByUser' is not running! So please check and restart manually!" + PAYLOAD="{\"channel\": \"$SLACK_CHANNEL\", \"username\": \"$SLACK_USERNAME\", \"icon_emoji\": \"$SLACK_ICON_EMOJI\", \"text\": \"$MESSAGE\"}" + curl -s -X POST -H "Content-type: application/json" --data "$PAYLOAD" "$SLACK_WEBHOOK_URL" + echo + echo "Slack notification sent successfully !!! " + echo + fi + done +fi + + +################################## Automation ######################### +#############################Improvised and automated this script using crontab like below as an advancement. +#I have used crontab to schedule the backup script to run for every 30 minutes. +#opened the crontab configuration by running : crontab -e and then you can run crontab -l to see the scheduled configurations. +#and added the following line at the end of the crontab file: */30 * * * * /root/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4/day4_part1__challange_solution.sh >> /root/backup_log.log 2>&1 + #the >> operator appends the output (both standard output and standard error) of the cron job to the specified log file (backup_log.log). The 2>&1 part ensures that both standard output (1) and standard error (2) are redirected to the log file. + + + diff --git a/Self-solutions/Day_4/day4_part1_solution_practice.sh b/Self-solutions/Day_4/day4_part1_solution_practice.sh new file mode 100644 index 0000000..9081457 --- /dev/null +++ b/Self-solutions/Day_4/day4_part1_solution_practice.sh @@ -0,0 +1,360 @@ +#!/bin/bash + +##################################################################### +# Script Name: day4_part1_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 3, 2023 +# Description: This script contains solution for Day 4 part-1 process monitoring and management as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day4_part1__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + + + +########################################### BashBlaze Scripting Challenge - Day 4 ####################################### +#Welcome to the Bash Scripting Challenge - Day 4! This challenge is designed to test your Bash scripting skills and problem-solving abilities in the context of process monitoring and management. + +############################################# Scenario ############### +#You are tasked with writing a Bash script that efficiently monitors a specific process on a Linux system. The script's primary goal is to ensure the process is always running, and if it unexpectedly stops, it should be restarted automatically. + +############################################ Task ############## +#1.Process Selection: +#The script should accept a command-line argument to specify the target process to monitor. For example: ./monitor_process.sh . + +#2.Process Existence Check: +#Implement a function that checks if the specified process is currently running on the system. +#If the process is running, print a message indicating its presence. + +#3.Restarting the Process: +#If the process is not running, implement a function that attempts to restart the process automatically. +#Print a message indicating the attempt to restart the process. +#Ensure the script does not enter an infinite loop while restarting the process. Limit the number of restart attempts. + +#4.Automation: +#Provide instructions on how to schedule the script to run at regular intervals using a cron job or any other appropriate scheduling method. + +#5.Documentation: +#Include clear and concise comments in the script to explain its logic and functionality. +#Write a separate document describing the purpose of the script, how to use it, and any specific considerations. + +#6.Bonus +#Implement a notification mechanism (e.g., email, Slack message) to alert administrators if the process requires manual intervention after a certain number of restart attempts. + +processNameByUser=$1 #taking first command line argument as a process name from user. + +check_if_process_running() { + + process_name=$1 + + if pgrep "$process_name" >/dev/null; then #checking if provided process is running or not + #The >/dev/null part in the shell script is used for redirecting the standard output of a command to the null dev -ice (/dev/null),which is a special device that discards any data written to it. + #If the process is running, pgrep will return a success status (exit code 0), and the output will be discarded. + # If the process is not running, pgrep will return a non-zero status, and the output will be discarded as well. + #The if statement checks the exit status, and based on that, it print the appropriate message without showing any output from the pgrep command itself. + return 0 + else + return 1 + fi +} + + +check_if_process_running "$processNameByUser" #passing the process name to the function + +if [ $? == 0 ]; then #comparing the output of above function usign $? with 0 means process is running. + echo + echo "Mentioned process '$processNameByUser' is running in the system !!!" + sudo systemctl status "$processNameByUser" #displaying the status of process. +else + echo + echo "Mentioned process '$processNameByUser' is not running in the system, Attempting to restart..." + echo + echo "Attempting restart to the process '$processNameByUser' automatically !" + + for ((restartAttempt=1; restartAttempt<=3; restartAttempt++)) #for loop to attempt for 3 times to restart the process + do + + echo "Attempt number: '$restartAttempt'" + + sudo systemctl start "$processNameByUser" #using systemctl command to start the service. + + + #checking if our restart attempt is succsfull or not. + check_if_process_running "$processNameByUser" + if [ $? == 0 ]; then + echo "process '$processNameByUser' is running successfully after restart attempt-'$restartAttempt' !!!" + echo + sudo systemctl status "$processNameByUser" #displaying the status of the process. + break #if success then we break the loop. + fi + + if [ $restartAttempt == 3 ]; then #after 3 attempts also if not restarted showing message. + echo "After 3 attempts to restart we could not able to start the process '$processNameByUser' please try manually !" + echo + echo "Sending slack notification !!!!!!!!!!!" + echo + SLACK_WEBHOOK_URL="https://hooks.slack.com/services/place-your-webhook-url" + SLACK_CHANNEL="#shell-scripting-projects" + SLACK_USERNAME="Process Monitor" + SLACK_ICON_EMOJI=":warning:" + MESSAGE=":warning: Process '$processNameByUser' is not running! So please check and restart manually!" + PAYLOAD="{\"channel\": \"$SLACK_CHANNEL\", \"username\": \"$SLACK_USERNAME\", \"icon_emoji\": \"$SLACK_ICON_EMOJI\", \"text\": \"$MESSAGE\"}" + curl -s -X POST -H "Content-type: application/json" --data "$PAYLOAD" "$SLACK_WEBHOOK_URL" + echo + echo "Slack notification sent successfully !!! " + echo + fi + done +fi + + +################################## Automation ######################### +#############################Improvised and automated this script using crontab like below as an advancement. +#I have used crontab to schedule the backup script to run for every 30 minutes. +#opened the crontab configuration by running : crontab -e and then you can run crontab -l to see the scheduled configurations. +#and added the following line at the end of the crontab file: */30 * * * * /root/BashBlaze-7-Days-of-Bash-Scripting-Challenge/Self-solutions/Day_4/day4_part1__challange_solution.sh >> /root/backup_log.log 2>&1 + #the >> operator appends the output (both standard output and standard error) of the cron job to the specified log file (backup_log.log). The 2>&1 part ensures that both standard output (1) and standard error (2) are redirected to the log file. + + +###################### practice #################### + +#practice-1 +#check if a particular process is running in shell scripting +#!/bin/bash + +# Process name to check +process_name="example_process" + +# Check if the process is running +if ps aux | grep -q "[${process_name:0:1}]${process_name:1}"; then + echo "The process '$process_name' is running." +else + echo "The process '$process_name' is not running." +fi +#sing the ps command and then filtering the output. +#we use ps aux to list all running processes and then use grep to search for the process name in the output +#The -q option of grep is used to make it quiet, so it doesn't print anything to the output. If the process is found, the if statement will be true, indicating that the process is running. Otherwise, it will print that the process is not running. + +#[${process_name:0:1}]${process_name:1} +#${process_name:0:1}: This part of the expression extracts the first character of the process_name variable. +#${process_name:1}: This part of the expression extracts all characters of process_name starting from the second character (index 1) to the end of the string. This effectively removes the first character from process_name, leaving only the rest of the characters. + +#checking the output of 'ps aux | grep [s]sh' +#it will print all the output that matchs with ssh but except grep itself due to [s] this bracket. +#ps aux: This command is used to list all running processes on the system. +#|: This is the pipe symbol, which is used to redirect the output of the ps aux command to the grep command. +#grep [s]sh: The grep command is used to search for a pattern in the input. In this case, it is searching for the pattern [s]sh. +#without the brackets, the grep command would normally match itself, resulting in an additional line in the output that includes the grep process. + + +#practice-2 +#check if a particular process is running or not in shell scripting using various commands like pgrep, ps, or pidof. +######Using pgrep: +if pgrep "process_name" >/dev/null; then + echo "Process is running." +else + echo "Process is not running." +fi + +#Using ps: +if ps -C "process_name" &>/dev/null; then + echo "Process is running." +else + echo "Process is not running." +fi + +#Using pidof: +if pidof "process_name" >/dev/null; then + echo "Process is running." +else + echo "Process is not running." +fi + + +# +#>/dev/null : usage +#The >/dev/null part in the shell script is used for redirecting the standard output of a command to the null device (/dev/null), which is a special device that discards any data written to it. + +#>: Redirects the standard output of the command to a file or device. +#/dev/null: A special device in Unix-like systems that discards any data written to it. +if pgrep "process_name" >/dev/null; then + echo "Process is running." +else + echo "Process is not running." +fi + + +#practice-3 +#for loop in shell scritping +# the for loop is used to iterate over a list of items and perform a set of commands for each item in the list. +for item in list +do + # Commands to be executed for each item +done + +#exaple-2 +for fruit in apple orange banana +do + echo "I like $fruit" +done + +#exaple-3 +for file in $(ls *.txt) +do + echo "Processing file: $file" + # Add commands to process the file here +done + + +#example-4 for loop with with break statement + +#he break statement is used within loops (like for or while loops) to prematurely exit the loop. When the break statement is encountered, the loop immediately terminates, and the control of the program moves to the first line of code following the loop. + +for number in 1 2 3 4 5 +do + echo "Processing number $number" + + # Check if the current number is equal to 3 + if [ "$number" -eq 3 ]; then + echo "Found number 3. Exiting loop." + break # Exit the loop when the number is 3 + fi +done + + +#loop 3 times and break + +#!/bin/bash + +# Initialize a counter variable +counter=0 + +# Loop 3 times +for ((i=1; i<=3; i++)) +do + echo "Iteration $i" + + # Increment the counter + ((counter++)) + + # Check if the counter is equal to 3 + if [ $counter -eq 3 ]; then + echo "Reached 3 iterations. Exiting loop." + break # Exit the loop + fi +done + + +#practice-5 +#practicing to send slack notification if process is not running in shell scripting +#To send a Slack notification from a shell script when a certain process is not running, + +#Set Up Incoming Webhook in Slack: +#Go to your Slack workspace. +#Click on your workspace name in the top left corner, then click "Settings & administration" > "Manage apps." +#In the "Apps" section, search for "Incoming Webhooks" and click on it. +#Click "Add to Slack" next to the channel where you want to receive the notifications. +#Follow the prompts to complete the setup. You'll get a webhook URL that you'll use in the shell script. + +#!/bin/bash + +# Function to check if the process is running +check_process() { + if pgrep -x "$1" >/dev/null; then + return 0 # Process is running + else + return 1 # Process is not running + fi +} + +# Replace these variables with your values +SLACK_WEBHOOK_URL="https://hooks.slack.com/services/YOUR/WEBHOOK/URL" +SLACK_CHANNEL="#your-slack-channel" +SLACK_USERNAME="Process Monitor" +SLACK_ICON_EMOJI=":warning:" + +# Process to check (replace "your-process" with the actual process name) +PROCESS_NAME="your-process" + +# Check if the process is not running +if ! check_process "$PROCESS_NAME"; then + # Send Slack notification + MESSAGE=":warning: Process '$PROCESS_NAME' is not running!" + PAYLOAD="{\"channel\": \"$SLACK_CHANNEL\", \"username\": \"$SLACK_USERNAME\", \"icon_emoji\": \"$SLACK_ICON_EMOJI\", \"text\": \"$MESSAGE\"}" + + curl -s -X POST -H "Content-type: application/json" --data "$PAYLOAD" "$SLACK_WEBHOOK_URL" +fi + +#Schedule the Script: +#To regularly check if the process is running and send notifications if it's not, you can schedule the script to run at a specific interval using cron. For example, to run the script every 5 minutes +*/5 * * * * /path/to/check_process.sh + + +#practice-6 +#practicing the switch case in shell scripting +#!/bin/bash + +day="Monday" + +case $day in + Monday) + echo "It's the start of the week." + ;; + Tuesday|Wednesday|Thursday) + echo "It's a weekday." + ;; + Friday) + echo "TGIF! It's Friday." + ;; + Saturday|Sunday) + echo "It's the weekend!" + ;; + *) + echo "Invalid day." + ;; +esac + +#the script checks the value of the variable day and executes different code blocks based on the day of the week. The esac marks the end of the case statement. + + +#exaple-2 +#infinite loop using a while loop with switch cases in shell scripting: +#!/bin/bash + +while true; do + echo "Enter your choice:" + echo "1. Option 1" + echo "2. Option 2" + echo "3. Option 3" + echo "4. Exit" + + read choice + + case $choice in + 1) + echo "You chose Option 1" + # Add your logic for Option 1 here + ;; + 2) + echo "You chose Option 2" + # Add your logic for Option 2 here + ;; + 3) + echo "You chose Option 3" + # Add your logic for Option 3 here + ;; + 4) + echo "Exiting..." + break + ;; + *) + echo "Invalid choice, please try again." + ;; + esac +done + + + + + diff --git a/Self-solutions/Day_4/day4_part2_challenge_solution.sh b/Self-solutions/Day_4/day4_part2_challenge_solution.sh new file mode 100755 index 0000000..03cb809 --- /dev/null +++ b/Self-solutions/Day_4/day4_part2_challenge_solution.sh @@ -0,0 +1,158 @@ +#!/bin/bash + +##################################################################### +# Script Name: day4_part2_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 3, 2023 +# Description: This script contains solution for Day 4 part-2 Monitoring Metrics Script with Sleep Mechanism as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day4_part2__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +#set -x +#################################################### Day-4 part2 Monitoring Metrics Script with Sleep Mechanism ############################# +####################### Challenge Description #################### +#This project aims to create a Bash script that monitors system metrics like CPU usage, memory usage, and disk space usage. The script will provide a user-friendly interface, allow continuous monitoring with a specified sleep interval, and extend its capabilities to monitor specific services like Nginx. + + +#Tasks +#Task 1: Implementing Basic Metrics Monitoring +#Write a Bash script that monitors the CPU usage, memory usage, and disk space usage of the system. The script should display these metrics in a clear and organized manner, allowing users to interpret the data easily. The script should use the top, free, and df commands to fetch the metrics. + +#Task 2: User-Friendly Interface +#Enhance the script by providing a user-friendly interface that allows users to interact with the script through the terminal. Display a simple menu with options to view the metrics and an option to exit the script. + +#Task 3: Continuous Monitoring with Sleep +#Introduce a loop in the script to allow continuous monitoring until the user chooses to exit. After displaying the metrics, add a "sleep" mechanism to pause the monitoring for a specified interval before displaying the metrics again. Allow the user to specify the sleep interval. + +#Task 4: Monitoring a Specific Service (e.g., Nginx) +#Extend the script to monitor a specific service like Nginx. Check if the service is running and display its status. If it is not running, provide an option for the user to start the service. Use the systemctl or appropriate command to check and control the service. + +#Task 5: Allow User to Choose a Different Service +#Modify the script to give the user the option to monitor a different service of their choice. Prompt the user to enter the name of the service they want to monitor, and display its status accordingly. + +#Task 6: Error Handling +#Implement error handling in the script to handle scenarios where commands fail or inputs are invalid. Display meaningful error messages to guide users on what went wrong and how to fix it. + +#Task 7: Documentation +#Add comments within the script to explain the purpose of each function, variable, and section of the code. Provide a clear and concise README file explaining how to use the script, the available options, and the purpose of the script. + +#Remember, the main goal of this challenge is to utilize various monitoring commands, implement a user-friendly interface, and create a script that is easy to understand and use. + +check_if_process_running() { + + process_name=$1 + + if pgrep "$process_name" >/dev/null; then #checking if provided process is running or not + #The >/dev/null part in the shell script is used for redirecting the standard output of a command to the null dev -ice (/dev/null),which is a special device that discards any data written to it. + #If the process is running, pgrep will return a success status (exit code 0), and the output will be discarded. + # If the process is not running, pgrep will return a non-zero status, and the output will be discarded as well. + #The if statement checks the exit status, and based on that, it print the appropriate message without showing any output from the pgrep command itself. + return 0 + else + return 1 + fi +} + + +while true; do + echo + echo "Main Menu" + echo + echo "------ Monitoring Metrics Script -------" + echo + echo "Choose below options" + echo " 1. View System Metrics " + echo " 2. Monitor a Specific Service " + echo " 3. Exit" + echo + + read -p "Enter your option: " userOption + + case $userOption in + 1) + + if [ "$reEnterTheMetrix" == 1 ]; then + echo + echo "Showing metrics again in 5 seconds... please wait! " + echo + sleep 5 #implementing the sleep mechanism if user wants to see metric details from second timewe will show the metrics detaisl with hiafter 5 seonds. + reEnterTheMetrix=0 + + fi + cpu_metric_usage=$( top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}' ) #the awk command is used to extract specific columns from the output of the top command. and '{print $2 + $4}': will sum the second %CPU column from the output of the top command and $4: Represents the fourth column of the input (in this case, the %us column, which represents the percentage of CPU used by user processes). + + cpu_metric_usage_percentage=$( printf "%.2f" "$cpu_metric_usage" ) #displaying only 2 decimal values. + + memory_metric_total=$( free | grep 'Mem:' | awk '{print $2}' ) #this free command will give us the memory usage details. and here we are taking 2nd and 3rd argument of free command output and calculating the percentage. + memory_metric_total_used=$( free | grep 'Mem:' | awk '{print $3}' ) + memory_metric_usage_percentage=$(echo "scale=2; $memory_metric_total_used / $memory_metric_total * 100" | bc) + #bc: basic calculator operation and to store only two decimal value as a output we are using scal=2. + + disk_usage_metric=$( df -h / | awk 'NR == 2 {print $5}' ) #here NR===2 means taking the second line from df -h / disk space outpur and extracting 5th argument as a disk usage metric. + + echo "CPU Usage: $cpu_metric_usage_percentage% Mem Usage: $memory_metric_usage_percentage% Disk Usage: $disk_usage_metric%" + + reEnterTheMetrix=1 + + ;; + + + 2) + + read -p "Enter the name of the service to monitor: " serviceNameByUser #taking service nameinput to monitor. + check_if_process_running "$serviceNameByUser" #passing the service name to the function. + + if [ $? == 0 ]; then #comparing the output of above function usign $? with 0 means service is running. + echo + echo "Mentioned process '$serviceNameByUser' is running in the system !!!" + sudo systemctl status "$serviceNameByUser" #displaying the status of process. + + else + echo + echo "Mentioned service '$serviceNameByUser' is not running in the system..." + echo + + read -p "Do you want to start $serviceNameByUser? (Y/N): " userOptionToStart + + if [ "$userOptionToStart" == "Y" ]; then + sudo systemctl start "$serviceNameByUser" #using systemctl command to start the service. + + check_if_process_running $serviceNameByUser + if [ $? == 0 ]; then + echo "'$serviceNameByUser' service started successfully!! " + sudo systemctl status $serviceNameByUser + echo + else + echo "Failed to start the service $serviceNameByUser. Please check the service name and try again!!!" + fi + else + echo "We did not try to start the service, Exiting..." + fi + fi + + ;; + + + + 3) + echo + echo "Exiting .." + echo + break + + ;; + + + *) + echo "Invalid option '$userOption'. please try again wtih the availiable options." + + ;; + esac + +done + + + diff --git a/Self-solutions/Day_4/day4_part2_solution_practice.sh b/Self-solutions/Day_4/day4_part2_solution_practice.sh new file mode 100644 index 0000000..889a715 --- /dev/null +++ b/Self-solutions/Day_4/day4_part2_solution_practice.sh @@ -0,0 +1,278 @@ +#!/bin/bash + +##################################################################### +# Script Name: day4_part2_challange_solution.sh +# Author: Salwad Basha Shaik +# Date: August 3, 2023 +# Description: This script contains solution for Day 4 part-2 Monitoring Metrics Script with Sleep Mechanism as part of BashBlaze: 7 Days of Bash Scripting Challenge. +# Usage: ./day4_part2__challange_solution.sh +# Email: salvathshaik786143@gmail.com +# LinkedIn: https://www.linkedin.com/in/salwad-basha-shaik/ +# Github: https://github.com/salvathshaik/ +##################################################################### + +#set -x +#################################################### Day-4 part2 Monitoring Metrics Script with Sleep Mechanism ############################# +####################### Challenge Description #################### +#This project aims to create a Bash script that monitors system metrics like CPU usage, memory usage, and disk space usage. The script will provide a user-friendly interface, allow continuous monitoring with a specified sleep interval, and extend its capabilities to monitor specific services like Nginx. + + +#Tasks +#Task 1: Implementing Basic Metrics Monitoring +#Write a Bash script that monitors the CPU usage, memory usage, and disk space usage of the system. The script should display these metrics in a clear and organized manner, allowing users to interpret the data easily. The script should use the top, free, and df commands to fetch the metrics. + +#Task 2: User-Friendly Interface +#Enhance the script by providing a user-friendly interface that allows users to interact with the script through the terminal. Display a simple menu with options to view the metrics and an option to exit the script. + +#Task 3: Continuous Monitoring with Sleep +#Introduce a loop in the script to allow continuous monitoring until the user chooses to exit. After displaying the metrics, add a "sleep" mechanism to pause the monitoring for a specified interval before displaying the metrics again. Allow the user to specify the sleep interval. + +#Task 4: Monitoring a Specific Service (e.g., Nginx) +#Extend the script to monitor a specific service like Nginx. Check if the service is running and display its status. If it is not running, provide an option for the user to start the service. Use the systemctl or appropriate command to check and control the service. + +#Task 5: Allow User to Choose a Different Service +#Modify the script to give the user the option to monitor a different service of their choice. Prompt the user to enter the name of the service they want to monitor, and display its status accordingly. + +#Task 6: Error Handling +#Implement error handling in the script to handle scenarios where commands fail or inputs are invalid. Display meaningful error messages to guide users on what went wrong and how to fix it. + +#Task 7: Documentation +#Add comments within the script to explain the purpose of each function, variable, and section of the code. Provide a clear and concise README file explaining how to use the script, the available options, and the purpose of the script. + +#Remember, the main goal of this challenge is to utilize various monitoring commands, implement a user-friendly interface, and create a script that is easy to understand and use. + +check_if_process_running() { + + process_name=$1 + + if pgrep "$process_name" >/dev/null; then #checking if provided process is running or not + #The >/dev/null part in the shell script is used for redirecting the standard output of a command to the null dev -ice (/dev/null),which is a special device that discards any data written to it. + #If the process is running, pgrep will return a success status (exit code 0), and the output will be discarded. + # If the process is not running, pgrep will return a non-zero status, and the output will be discarded as well. + #The if statement checks the exit status, and based on that, it print the appropriate message without showing any output from the pgrep command itself. + return 0 + else + return 1 + fi +} + + +while true; do + echo + echo "Main Menu" + echo + echo "------ Monitoring Metrics Script -------" + echo + echo "Choose below options" + echo " 1. View System Metrics " + echo " 2. Monitor a Specific Service " + echo " 3. Exit" + echo + + read -p "Enter your option: " userOption + + case $userOption in + 1) + + if [ "$reEnterTheMetrix" == 1 ]; then + echo + echo "Showing metrics again in 5 seconds... please wait! " + echo + sleep 5 #implementing the sleep mechanism if user wants to see metric details from second timewe will show the metrics detaisl with hiafter 5 seonds. + reEnterTheMetrix=0 + + fi + cpu_metric_usage=$( top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}' ) #the awk command is used to extract specific columns from the output of the top command. and '{print $2 + $4}': will sum the second %CPU column from the output of the top command and $4: Represents the fourth column of the input (in this case, the %us column, which represents the percentage of CPU used by user processes). + + cpu_metric_usage_percentage=$( printf "%.2f" "$cpu_metric_usage" ) #displaying only 2 decimal values. + + memory_metric_total=$( free | grep 'Mem:' | awk '{print $2}' ) #this free command will give us the memory usage details. and here we are taking 2nd and 3rd argument of free command output and calculating the percentage. + memory_metric_total_used=$( free | grep 'Mem:' | awk '{print $3}' ) + memory_metric_usage_percentage=$(echo "scale=2; $memory_metric_total_used / $memory_metric_total * 100" | bc) + #bc: basic calculator operation and to store only two decimal value as a output we are using scal=2. + + disk_usage_metric=$( df -h / | awk 'NR == 2 {print $5}' ) #here NR===2 means taking the second line from df -h / disk space outpur and extracting 5th argument as a disk usage metric. + + echo "CPU Usage: $cpu_metric_usage_percentage% Mem Usage: $memory_metric_usage_percentage% Disk Usage: $disk_usage_metric%" + + reEnterTheMetrix=1 + + ;; + + + 2) + + read -p "Enter the name of the service to monitor: " serviceNameByUser #taking service nameinput to monitor. + check_if_process_running "$serviceNameByUser" #passing the service name to the function. + + if [ $? == 0 ]; then #comparing the output of above function usign $? with 0 means service is running. + echo + echo "Mentioned process '$serviceNameByUser' is running in the system !!!" + sudo systemctl status "$serviceNameByUser" #displaying the status of process. + + else + echo + echo "Mentioned service '$serviceNameByUser' is not running in the system..." + echo + + read -p "Do you want to start $serviceNameByUser? (Y/N): " userOptionToStart + + if [ "$userOptionToStart" == "Y" ]; then + sudo systemctl start "$serviceNameByUser" #using systemctl command to start the service. + + check_if_process_running $serviceNameByUser + if [ $? == 0 ]; then + echo "'$serviceNameByUser' service started successfully!! " + sudo systemctl status $serviceNameByUser + echo + else + echo "Failed to start the service $serviceNameByUser. Please check the service name and try again!!!" + fi + else + echo "We did not try to start the service, Exiting..." + fi + fi + + ;; + + + + 3) + echo + echo "Exiting .." + echo + break + + ;; + + + *) + echo "Invalid option '$userOption'. please try again wtih the availiable options." + + ;; + esac + +done + + +############################################ practice #################### + + +#practice-1 +#practicing To get CPU, memory, and disk usage in shell scripting, you can use various commands and tools available in Linux +######CPU Usage: +#Use the top command with -n1 to get a one-time report of CPU usage: + +top -n1 + +#use the mpstat command to get CPU statistics: +mpstat + + +### Memory Usage: +#Use the free command to get memory usage: + +free -h + +#use the top command to see memory usage along with other statistics: +top + +#### Disk Usage: + +#Use the df command to get disk usage information: +df -h + +#use the du command to get disk usage of specific directories: +du -h /path/to/directory + +#to capture the output of these commands in a shell script +#use command substitution with backticks or $(): +#!/bin/bash + +cpu_usage=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}') +memory_usage=$(free -h | grep 'Mem:' | awk '{print $3}') +disk_usage=$(df -h | grep '/dev/sda1' | awk '{print $5}') + +echo "CPU Usage: $cpu_usage" +echo "Memory Usage: $memory_usage" +echo "Disk Usage: $disk_usage" + + +#practice-2 +#practicing to get CPU, memory, and disk usage in percentages in shell scripting, +#!/bin/bash + +# CPU Usage +cpu_usage=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}') +cpu_usage_percentage=$(printf "%.2f" "$cpu_usage") + +# Memory Usage +memory_total=$(free | grep 'Mem:' | awk '{print $2}') +memory_used=$(free | grep 'Mem:' | awk '{print $3}') +memory_usage_percentage=$(echo "scale=2; $memory_used / $memory_total * 100" | bc) + +# Disk Usage +disk_usage=$(df -h | grep '/dev/sda1' | awk '{print $5}' | cut -d'%' -f1) + +echo "CPU Usage: $cpu_usage_percentage%" +echo "Memory Usage: $memory_usage_percentage%" +echo "Disk Usage: $disk_usage%" + + + +#explainig awk '{print $2 + $4}' + +#awk: The command itself, which stands for "Aho, Weinberger, and Kernighan." It is a versatile text processing tool commonly used in shell scripting to manipulate and extract data from text files or command output. +#'{print $2 + $4}': This is the awk script enclosed in single quotes. It consists of a single awk action that instructs awk on what to do with each input line. +#it basically sum the 2nd and 4th arugment + +#explaining the line also disk_usage=$(df -h | grep '/dev/sda1' | awk '{print $5}' | cut -d'%' -f1) +#df -h: This command is used to display disk space usage on Linux systems. The -h option stands for "human-readable," which means the output will be in a human-friendly format, displaying sizes in KB, MB, GB, etc., instead of raw blocks. + +#grep '/dev/sda1': The grep command is used to search for a specific pattern or string in the output of the df command. In this case, we are searching for the line that corresponds to the /dev/sda1 partition, which is usually the main system partition. + +#awk '{print $5}': Just like in the previous explanation, awk is used to extract a specific column from the input. In this case, it extracts the fifth column, which represents the "Use%" column in the output of df. The "Use%" column shows the percentage of disk space used. + +#cut -d'%' -f1: The cut command is used to extract a specific portion of each line of text. In this case, we use it to remove the percentage sign (%) from the extracted "Use%" value obtained from the awk command. The -d'%' option specifies that the delimiter is the percentage sign, and -f1 indicates that we want to keep only the first field (before the percentage sign). + +#The final result of this command chain is the disk usage percentage of the /dev/sda1 partition, which is then assigned to the disk_usage variable in the shell script. + + +#exaple-2 +#To find the disk usage of the main system partition, you can modify the command to search for the root file system using the / mount point: +disk_usage=$(df -h / | awk 'NR == 2 {print $5}' | cut -d'%' -f1) +#we use / as the argument to df to specify the root file system. The awk command is used to extract the disk usage percentage from the second line of the df output (the first line contains headers). The cut command is then used to remove the percentage sign (%) from the extracted value. +#basically cut will remove the '%' symbol from the output +#replace / with the appropriate mount point in the df command. + +#awk command, NR == 2 is a pattern that specifies a condition for selecting a specific line from the input +#NR is a built-in variable in awk that represents the current record (i.e., the line number). +#NR == 2 checks if the current line being processed is the second line of the input. +#cut -d'%' -f1: This cut command removes the percentage sign "%" from the disk usage percentage printed by the awk command, leaving only the numeric value. + + +#%.2f means? +#% is the formatting operator that indicates that a format specification follows. +#.2 is the precision specification, which tells printf to display two decimal places after the decimal point. +#f is the format character that specifies the format as a floating-point number. + + +#explaining the $(echo "scale=2; $memory_used / $memory_total * 100" | bc) + +#The scale=2 sets the decimal precision to two decimal places, indicating that the result should have two digits after the decimal point. +#$memory_used: This is a variable containing the amount of used memory. +#$memory_total: This is a variable containing the total amount of memory available. +#| bc: The | (pipe) symbol is used to redirect the output of the echo command to the bc command. bc stands for "basic calculator" and is a command-line calculator that can perform arithmetic operations. + + + +# + + + + + + + + + diff --git a/Self-solutions/Day_4/practice-1.sh b/Self-solutions/Day_4/practice-1.sh new file mode 100755 index 0000000..86b3a23 --- /dev/null +++ b/Self-solutions/Day_4/practice-1.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# Initialize a counter variable +counter=0 + +# Loop 3 times +for ((i=1; i<=3; i++)) +do + echo "Iteration $i" + + # Increment the counter + ((counter++)) + + # Check if the counter is equal to 3 + if [ $counter -eq 3 ]; then + echo "Reached 3 iterations. Exiting loop." + break # Exit the loop + fi +done + diff --git a/Self-solutions/Day_4/readme.txt b/Self-solutions/Day_4/readme.txt new file mode 100644 index 0000000..610f5fe --- /dev/null +++ b/Self-solutions/Day_4/readme.txt @@ -0,0 +1 @@ +please run 'day4_part1_challenge_solution.sh' and day4_part2_challenge_solution.sh files for challenge solutions.