Day 5: Advanced Linux Shell Scripting for DevOps Engineers with User Management
Hello, DevOps Enthusiasts! π
As part of my #90DaysOfDevOps challenge, I dived into Advanced Linux Shell Scripting today, focusing on directory creation, backups, automation with crontab, and user management. Here's a detailed walkthrough of today's tasks and my solutions.
π Task 1: Create Directories Using Shell Script
Objective:
Create a bash script createDirectories.sh
to generate a specified number of directories dynamically based on user inputs.
Code:
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 25/11/24
Description : This script takes three arguments and creates a specified number of directories at once.
Example :
./createDirectories.sh day 1 90 β Creates directories day1, day2, ..., day90.
Info
# Loop through the range of directory numbers
for i in $(seq $2 $3); do
mkdir "$1$i"
done
Example Execution:
./createDirectories.sh day 1 90
β Createsday1
today90
../createDirectories.sh Movie 20 50
β CreatesMovie20
toMovie50
.
Check out the script and output images below:
π Task 2: Backup Script
Objective:
Write a script to back up a directory or file and save it in a predefined backup folder.
Code:
#!/bin/bash
<<Info
Author : Amitabh Soni
Date : 25/11/24
Description : This script creates a zip backup of a directory or file and stores it in the backup directory.
Info
# Function to create a backup
function create_backup() {
timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
target_dir="/home/ubuntu/Day-05/backup"
backup_file="${target_dir}/backup_${timestamp}.zip"
# Create the zip file
zip -r "$backup_file" "$1"
if [ $? -eq 0 ]; then
echo "Backup created: $backup_file"
else
echo "Error: Backup failed."
fi
}
create_backup "$1"
Steps:
Save the script as
backup.sh
.Run it with the directory or file you want to back up:
./backup.sh /path/to/directory_or_file
Output:
Script execution screenshot:
Backup folder after execution:
π Task 3: Automating Backups with Cron and Crontab
Objective:
Automate the backup.sh
script to run at regular intervals using crontab.
Steps:
Open the crontab editor:
crontab -e
Add the following line to run the backup every minute:
* * * * * /path/to/backup.sh /path/to/directory_or_file
Verifications:
Watching real-time backups with
watch ls
:Final backup check:
π Task 4: User Management in Linux
Objective:
Create two users and display their usernames.
Steps:
Use
adduser
command to create users:sudo adduser username1 sudo adduser username2
Display usernames:
cut -d: -f1 /etc/passwd | tail -2
Execution:
Adding users:
Password setup:
π‘ Key Learnings:
Leveraged shell scripting for dynamic tasks like directory creation and backups.
Automated routine tasks with cron and crontab.
Explored the fundamentals of Linux user management.
π Check Out My Progress:
GitHub Repo (Pull request)
Stay tuned for more updates from my #90DaysOfDevOps challenge! π
What do you think about these tasks? Feel free to share your thoughts or ask questions in the comments below! π