5. Advanced Linux Shell Scripting for DevOps Engineers with User management

Sunil PrasadSunil Prasad
2 min read

Task 1: Creating Dynamic Directories

Here's a bash script for the first task, creating directories with a dynamic name:

#!/bin/bash 

if [ "$#" -ne 3 ]; then 
    echo "Usage: $0 <directory_name> <start_number> <end_number>" 
    exit 1 
fi

directory_name="$1" 
start_number="$2" 
end_number="$3" 

if [ "$start_number" -gt "$end_number" ]; then echo "Start number should be less than or equal to end number." exit 1 
fi 

for 
  ((i=start_number; i<=end_number; i++)); do         dir_name="${directory_name}${i}" 
mkdir "$dir_name" 
echo "Created directory: $dir_name" 
done

Save this script in a file, e.g., createDirectories.sh, and make it executable using chmod +x createDirectories.sh.

To run the script, use the following commands:

./createDirectories.sh day 1 90

This will create directories named day1, day2, day3, and so on up to day90.

Task 2: Backup Your Work

For the second task, creating a backup script, you can create a script like this:

#!/bin/bash 

# Set the source directory to backup source_directory="/path/to/your/source"

# Set the backup directory 
backup_directory="/path/to/your/backup"

# Create a timestamp to include in the backup folder name 
timestamp=$(date +%Y%m%d%H%M%S)

# Create a backup file with a timestamp 
final_file="$backup_directory/file_backup-$timestamp.tgz"

# Create the backup
if tar czf "$final_file" -C "$source_directory" .; then
  echo "Backup Complete"
else
  echo "Backup Failed"
fi

Save this script in a file, e.g., backup.sh, and make it executable using chmod +x backup.sh.

To automate this backup script using Cron, you can add an entry to your user's crontab by running crontab -e and adding a line like this to run the script daily at a specific time:

0 2 * * * /path/to/backup.sh

This will run the backup.sh script every day at 2:00 AM. Adjust the timing as needed.

Task 3: User Management in Linux

For the third task, you can create two users and display their usernames using the following commands:

# Create the first user 
sudo useradd user1 

# Set a password for the first user 
sudo passwd user1 

# Create the second user 
sudo useradd user2 

# Set a password for the second user 
sudo passwd user2 

# Display the usernames 
echo "User 1: user1" echo "User 2: user2"

This will create two users, user1 and user2, and display their usernames as specified.

Thank you for reading this article...

0
Subscribe to my newsletter

Read articles from Sunil Prasad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sunil Prasad
Sunil Prasad

Aspiring Devops Engineer who have proficient knowledge AWS || LINUX || GIT || GITHUB || ANSIBLE || DOCKER || TERRAFORM || JENKINS || KUBERNETES || PROMETHEUS || GRAFANA || UBUNTU/REDHAT || PYTHON ||