Advanced Linux Shell Scripting for DevOps

Advanced Linux Shell Scripting for DevOps

📍if

The basic syntax for the if statement is as follows:

COPY

if [[ condition ]]
then
    # Code to execute if the condition is true
else
    # Code to execute if the condition is false (optional)
fi

We will compare the two numbers by passing it as an argument, and get to see the results which is the bigger number among them. The script for comparing two numbers is as follows:

Here,

The scripts always start with #!/bin/bash

-gt: greater than, and the code syntax end with fi word.

📍elif

the elif statement (short for "else if") is used to add additional conditions to the "if" statement. It allows you to test multiple conditions sequentially after the initial "if" condition, providing alternative branches for different scenarios.

The basic syntax for the elif statement is as follows:

COPY

if [ condition1 ]; then
    # Code to execute if condition1 is true
elif [ condition2 ]; then
    # Code to execute if condition2 is true
elif [ condition3 ]; then
    # Code to execute if condition3 is true
# Add more "elif" blocks as needed
else
    # Code to execute if none of the conditions are true
fi

Each elif block is evaluated only if the preceding conditions in the "if" and other elif blocks are false. If one of the conditions is true, the corresponding block of code will be executed, and the rest of the "if-elif-else" statement will be skipped.

Here, again we will compare three numbers using the following script:

📍Creating Mutliple Directories

For creating a normal directory we use command mkdir <directory_name> Similarily we will add this in a Scripting file.

The script to create multiple directories is as follows:

📍tar

tar is a command-line utility used to create, view, and extract archive files in the tar format. The name "tar" stands for "tape archive," . However, nowadays, tar is commonly used for creating and manipulating archive files on disk as well.

The basic syntax of the tar command is as follows:

COPY

tar [options] [archive-file] [files/directories...]

Here are some commonly used options for the tar command:

  • c: Create a new archive.

  • x: Extract files from an archive.

  • v: Verbose mode, which displays the list of processed files.

  • f: Specify the filename of the archive.

📍Add users

To add a user we use the command sudo useradd -m <username>. Hence the user is created.Similarly we will use this in the script as well syntax and use for loop as shown below.

The basic syntax of the for loop in bash (a commonly used shell) is as follows:

COPY

for variable in list
do
    # Code to be executed for each item in the list
done

We have added two users named Ank and Pratik through the following script. After running the script there will be a prompt asking for a username and password. The scripts also includes where the added users are shown.

📍References

  1. Github

  2. Google