"Mastering Shell Scripting: Simplify Folder Creation, Backup Management, and User Administration"

Abhishek RaneAbhishek Rane
6 min read

What is a Shell script?

A shell script is a type of computer program designed to be run by a Unix shell, such as Bash (Bourne Again Shell), sh (Bourne Shell), csh (C Shell), ksh (Korn Shell), or zsh (Z Shell). It is essentially a text file containing a sequence of shell commands and constructs that are interpreted and executed by the shell.

Shell scripts are commonly used for automating tasks, performing system administration tasks, and creating simple utilities. They are versatile and can interact with the operating system, manipulate files and directories, execute programs, handle user input, and perform various other tasks.

Script for Creation of Dynamic Folders.

Here, We will be creating a script which will create multiple directories for us with desired name and number of directories we want.

💡
#Before executing any of the scripts , make sure you make your script executable by typing <scriptname> +x OR chmod 755 <scriptname>

Lets have a look at the script:

#!/bin/bash

echo "This script is for creating custom directories"
echo "Enter the root directory name:"
read root_dir

mkdir "$root_dir" && cd "$root_dir"

echo "Now enter the custom directory name you want to create:"
read custom_dir

echo "Enter the starting number for your directories:"
read start
echo "Enter the ending number for your directories:"
read end

for ((num=start ; num<=end ; num++))
do
    mkdir "${custom_dir}${num}"
done

The output will be as follows:

Script for taking a backup of a particular folder.

These days it has become very important for taking backups of the present files in production environment as there are various users working on VM's and it may happen that an important file/folder may get deleted from a user. Hence for a safer side , we create a shell script which will help us to take backup of Important files.

With this , lets proceed to create a script which will take backup of a particular folder and store in a defined path.

We first start with creating a shell script file with "backup.sh" where .sh will represent it as shell script file.

The backup will be taken in form of a compressed .tar file for efficient space management.

#!/bin/bash

<< comment
This will take backup of
scripts folder
comment

src_dir="/home/ubuntu/scripts"
tgt_dir="/home/ubuntu/scripts/backups"

backup_filename="backup_$(date +%Y-%m-%d_%H_%M).tar.gz"

echo "Backup file will be created as $backup_filename"
echo "Backing up files..."

tar -czvf "${tgt_dir}/${backup_filename}" "$src_dir"
echo "Backup Completed and available at ${tgt_dir}"

In this way , we have taken backup of "scripts" folder and stored inside "backups" folder.

PFB:

Automating the backup:

This process can be automated using a cronjob.

minute hour day month day_of_week <path for you script>
OR
* * * * *

We can take reference of the image below for scheduling the script using cronjob.

For this, just type crontab -e and there you can fill in your entry for the job.

Adding some useful commands to manage your cronjobs:

  • crontab -e: Edit the crontab file, or create one if it doesn’t already exist.

  • crontab -l: Display crontab file contents.

  • crontab -r: Remove your current crontab file.

  • crontab -i: Remove your current crontab file with a prompt before removal.

Let's put an entry into cronjob which will run the script at 8:00 PM every Friday .

     # Run the backup script every Friday at 8:00 p.m
     0 20 * * 5 </path/to/backup-script.sh>

How this will work:

  • 0: This specifies the minute when the cron job will run (0th minute).

  • 20: This specifies the hour when the cron job will run (8 PM).

  • *: This specifies that the cron job will run every day of the month.

  • *: This specifies that the cron job will run every month.

  • 5: This specifies that the cron job will run only on Fridays (since Sunday is 0, Friday is 5).

So, the cron expression 0 20 * * 5 means "run the cron job at 8:00 PM every Friday."

Shell Script for User Management.

As we all know In production , there keeps on getting entry and exit of various new/old users or there are login issues for existing users too. For handling such problems , there comes user management scripts which helps in onboarding of new users or modifying of existing ones. Let us learn how to automate user account creation, modification, and deletion, streamlining administrative tasks and enhancing system security.

Below is the script for user management:

#!/bin/bash

add_user() {
    read -p "Enter username to be created: " username
    # Check if user already exists

    if grep -q "^$username:" /etc/passwd; then
        echo "User $username already exists."
    else
        read -s -p "Enter password: " password
        echo
        echo "Creating username with given password..."
        useradd -m $username
        echo "$username:$password" | chpasswd
        echo "User $username created."
    fi
}
change_passwd() {
    read -p "Enter the username to change password: " username
    read -s -p "Enter password: " password
    echo "Changing password..."
    echo "$username:$password" | chpasswd
    echo "Password changed for user $username."
}
user_del() {
    read -p "Enter username to be deleted: " username
    if grep -q "^$username:" /etc/passwd; then
        userdel -r $username
        echo "User $username deleted successfully."
    else
        echo "No such user found."
    fi
}
# Main menu function
main_menu() {
    echo "User Management Menu"
    echo "1. Add User"
    echo "2. Change Password"
    echo "3. Delete User"
    echo "4. Exit"
    read -p "Enter your choice: " choice
    case $choice in
        1) add_user ;;
        2) change_passwd ;;
        3) user_del ;;
        4) echo "Exiting." ;;
        *) echo "Invalid choice." ;;
    esac
}
# Call main menu function
main_menu

In this way , you can manage users for addition , deletion and password deletion.

Below snip displays the working of the same:

Advantages of using these scripts:

  1. Automation: Shell scripting allows you to automate repetitive tasks, saving time and reducing the chance of errors. For example, you can create a script to back up files, clean up temporary files, or install software.

  2. Customization: You can tailor scripts to suit your specific needs. Whether it's configuring system settings, managing files, or executing complex commands, shell scripting provides flexibility to customize tasks according to your requirements.

  3. Efficiency: With shell scripting, you can execute multiple commands in sequence or in parallel, streamlining workflows and increasing efficiency. This is particularly useful for tasks that involve a series of steps or require simultaneous execution of commands.

  4. Reduced Efforts: Implementing these scripts can significantly reduce repetitive tasks, leading to time savings and minimizing the need for users to manually enter multiple commands repeatedly.

Summary:
In this way we created our scripts for various kind of tasks. This scripts can be helpful in the environment to automate many of he manual works and can save time and efforts of employees.

Stay Tuned for More Projects: Be sure to keep an eye on our page for upcoming projects similar to this one. We're committed to providing you with valuable resources to enhance your learning journey. Happy Scripting!! :)

10
Subscribe to my newsletter

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

Written by

Abhishek Rane
Abhishek Rane

I am a Linux Admin performing various Linux operations. Currently looking forward to excel more in my field.