Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Challenges/Day_1/Day_1_Basics.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/bin/bash

# Welcome to Day 1 of the Bash Scripting Challenge! Today, we will cover the basics of bash scripting to get you started. Let's dive in:

# Task 1: You can add comments by adding '#' before any sentence to make it a comment. Usually it is a best practice to add comments before the program/ code to let reader know what next line will do.
# or we can add comments along with code line for better understading of that particular line of code.

# Task 2: Echo. The echo command is used to display messages on the terminal.
# Let's print a message of our choice.
echo "Welcome to the World of Bash Scripting!"
echo ''

# Task 3: Variables. Variables in bash are used to store data and can be referenced by their name.
# Let's create two variables 'num1' and 'num2' and assigns some integer values to them.
# CAUTION! : DO NOT ADD SPACES WHILE ASSIGNING VALUES TO VARIABLES.
var1=5
var2=10

name='Randhawa Verma' # You can assign string as well to the variables just like we added integers above.


# Task 4: Using Variables.
# Let's Create a bash script that takes above created two numbers as input and prints their sum using those variables.
# First we will create a new variable called sum and add the two numbers. INFO - Use $ sign before variable name to use the variable.
sum=$(( $var1 + $var2 )) #$(()) will evaluate the expression we provided in it.
echo 'Total of the two variables' $var1 'and' $var2 'is:' $sum
echo ''


# Task 5: Using Built-in Variables. Bash provides several built-in variables that hold useful information.
# Let's Use following three built-in - $#, $@ & $?. When running script, we need to provide arguments like this ./Day1_script.sh 1 2 3 4
echo 'Using $#, Numbers you entered total are:' $#
echo 'Using $@, You entered following numbers:' $@
echo 'Using $?, Let us confirm if last command was successful or not. (0 is for Yes)' $?
echo ''

# $# = Tells number of arguments passed.
# $@ = What parameters were passed to the command line.
# $? = Was last command successful. If Answer is 0 that means 'yes'.


# Task 6: Wildcards. Wildcards are special characters used to perform pattern matching when working with files.
# Let's create a bash script that lists all the files with a specific extension in a directory.
# let's print all script files i.e. to print files with .sh extension.
echo "Listing all scripts in the current directory- "
ls *.sh
70 changes: 33 additions & 37 deletions Challenges/Day_2/backup_with_rotation.sh
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
#!/bin/bash

# Function to display usage information and available options
function display_usage {
echo "Usage: $0 /path/to/source_directory"
}

# Check if a valid directory path is provided as a command-line argument
if [ $# -eq 0 ] || [ ! -d "$1" ]; then
echo "Error: Please provide a valid directory path as a command-line argument."
display_usage
exit 1
# Asking user to provide the directory path to take backup of
read -p "Please provide path to take back up of: " src_dir
echo $src_dir

# Creating back up folder
echo "Creating back up..."

# Setting Current Time using date command
current_time=$(date "+%Y-%m-%d_%H-%M-%S")
# echo "Current Time : $current_time"

# Creating back up folder by appending current time with backup_
backup_folder=$src_dir/backup_$current_time

# Getting count of back up folders
file_count=$(ls -l $src_dir | awk '/backup_/' | wc -l)
# echo $file_count

# Getting the name of oldest file
oldest_file=$(ls -l $src_dir | awk '/backup_/ {print $9}' | head -1)
# echo $oldest_file

# Using condition to check if there are 3 back up folders already present then remove the oldest one and add the new.
if [ $file_count -eq 3 ]
then
echo "Removing Oldest File: $oldest_file"
rm -r "$src_dir/$oldest_file"
fi

# Directory path of the source directory to be backed up
source_dir="$1"

# Function to create a timestamped backup folder
function create_backup {
local timestamp=$(date '+%Y-%m-%d_%H-%M-%S') # Get the current timestamp
local backup_dir="${source_dir}/backup_${timestamp}"

# Create the backup folder with the timestamped name
mkdir "$backup_dir"
echo "Backup created successfully: $backup_dir"
}

# Function to perform the rotation and keep only the last 3 backups
function perform_rotation {
local backups=($(ls -t "${source_dir}/backup_"* 2>/dev/null)) # List existing backups sorted by timestamp

# Check if there are more than 3 backups
if [ "${#backups[@]}" -gt 3 ]; then
local backups_to_remove="${backups[@]:3}" # Get backups beyond the last 3
rm -rf "${backups_to_remove[@]}" # Remove the oldest backups
fi
}

# Main script logic
create_backup
perform_rotation
# using rysnc to copy src folder and copying it into backup folder. rsync helped in excluding older back up folders.
rsync -ar $src_dir/. $backup_folder --exclude /backup*

echo "Backup created: $backup_folder"


38 changes: 22 additions & 16 deletions Challenges/Day_2/explorer.sh
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
#!/bin/bash

# Part 1: File and Directory Exploration
echo "Welcome to the Interactive File and Directory Explorer!"
# Welcome Message for the user
echo 'Welcome to the Interactive File and Directory Explorer!'
echo ''
echo 'Files and Directories in the Current Path:'
# echo ''

while true; do
# List all files and directories in the current path
echo "Files and Directories in the Current Path:"
ls -lh
# Using ls command to list all the content in current path.
# -lhR flags with print items in listing format showing size in human readable format recursively.
# awk command will filter out only file or folder name and their size.
# sed will delete the lines with blank () in the output.
ls -lhR | awk 'NF>0 {print $9 "("$5")"}' | sed '/()/d'

# Part 2: Character Counting
read -p "Enter a line of text (Press Enter without text to exit): " input

# Exit if the user enters an empty string
if [ -z "$input" ]; then
echo "Exiting the Interactive Explorer. Goodbye!"
break
# Creating a while loop which will ask user to provide any line of text and as show total characters in that line as output.
# Pressing Enter key will exit out of the program.
while true
do
read -p "Enter a line of text (Press Enter without text to exit): " line_of_text
if [[ $line_of_text = "" ]];
then echo "Exiting the Interactive Explorer. Goodbye!"
break
else
echo "No. of characters: ${#line_of_text}"
fi

# Calculate and print the character count for the input line
char_count=$(echo -n "$input" | wc -m)
echo "Character Count: $char_count"
done


155 changes: 67 additions & 88 deletions Challenges/Day_3/user_management.sh
Original file line number Diff line number Diff line change
@@ -1,94 +1,73 @@
#!/bin/bash

# Function to display usage information and available options
function display_usage {
echo "Usage: $0 [OPTIONS]"
echo "Options:"
echo " -c, --create Create a new user account."
echo " -d, --delete Delete an existing user account."
echo " -r, --reset Reset password for an existing user account."
echo " -l, --list List all user accounts on the system."
echo " -h, --help Display this help and exit."
############################################################
# Help #
############################################################
Help()
{
# Display Help
echo "Usage: ./user_management.sh [OPTIONS]"
echo
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 "-i, --info Display Extra User Info."
echo "-u, --uname Change username."
}

# Function to create a new user account
function create_user {
read -p "Enter the new username: " username

# Check if the username already exists
if id "$username" &>/dev/null; then
echo "Error: The username '$username' already exists. Please choose a different username."
else
# Prompt for password (Note: You might want to use 'read -s' to hide the password input)
read -p "Enter the password for $username: " password
############################################################
# Main program #
############################################################

# Create the user account
useradd -m -p "$password" "$username"
echo "User account '$username' created successfully."
fi
}

# Function to delete an existing user account
function delete_user {
read -p "Enter the username to delete: " username

# Check if the username exists
if id "$username" &>/dev/null; then
userdel -r "$username" # -r flag removes the user's home directory
echo "User account '$username' deleted successfully."
else
echo "Error: The username '$username' does not exist. Please enter a valid username."
fi
}

# Function to reset the password for an existing user account
function reset_password {
read -p "Enter the username to reset password: " username

# Check if the username exists
if id "$username" &>/dev/null; then
# Prompt for password (Note: You might want to use 'read -s' to hide the password input)
read -p "Enter the new password for $username: " password

# Set the new password
echo "$username:$password" | chpasswd
echo "Password for user '$username' reset successfully."
else
echo "Error: The username '$username' does not exist. Please enter a valid username."
fi
}

# Function to list all user accounts on the system
function list_users {
echo "User accounts on the system:"
cat /etc/passwd | awk -F: '{ print "- " $1 " (UID: " $3 ")" }'
}

# Check if no arguments are provided or if the -h or --help option is given
if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
display_usage
exit 0
fi

# Command-line argument parsing
while [ $# -gt 0 ]; do
case "$1" in
-c|--create)
create_user
;;
-d|--delete)
delete_user
;;
-r|--reset)
reset_password
;;
-l|--list)
list_users
;;
*)
echo "Error: Invalid option '$1'. Use '--help' to see available options."
exit 1
;;
esac
shift
done
if [ "$1" = "--create" -o "$1" = "-c" ]; then
read -p "Enter username: " username
read -p "Enter password: " userpass
if id "$username" >/dev/null 2>&1; then
echo "ERROR: User already present. Please choose a different username."
else
sudo useradd $username
echo "SUCCESS: User account for $username created Successfully."
fi
elif [ "$1" = "--delete" -o "$1" = "-d" ]; then
read -p "Enter username to delete: " username
read -p "Please confirm (y/n): " option
if [ $option = 'y' ]; then
if id "$username" >/dev/null 2>&1; then
sudo userdel $username
echo "SUCCESS: User deleted Successfully."
else
echo 'ERROR: User not present. Please Check.'
fi
else echo 'Cancelling User Deletion Process.'
fi
elif [ "$1" = "--reset" -o "$1" = "-r" ]; then
read -p "Enter the username to reset password: " username
if id "$username" >/dev/null 2>&1; then
read -p 'Enter new password: ' userpass
sudo chpasswd <<< "$username:$userpass"
echo 'SUCCESS: Password reset successfully.'
else echo 'ERROR: User not present'
fi
elif [ "$1" = "--list" -o "$1" = "-l" ]; then
cat /etc/passwd | awk -F':' '{print $1 " (ID: "$3")"}'
elif [ "$1" = "--info" -o "$1" = "-i" ]; then
read -p "Enter the username to get additional info: " username
if id "$username" >/dev/null 2>&1; then
echo '====== USER INFO ======'
lslogins -u $username
else echo 'ERROR: User not present'
fi
elif [ "$1" = "--uname" -o "$1" = "-u" ]; then
read -p "Enter the username to change: " username
if id "$username" >/dev/null 2>&1; then
read -p "Enter new username: " newuser
echo 'SUCCESS: Username updated successfully.'
sudo usermod -l $newuser $username
else echo 'ERROR: User not present'
fi
elif [ "$1" = "" -o "$1" = "--help" -o "$1" = "-h" ]; then Help
fi