DEV Community

Cover image for Automation with Bash Script Pt 2.
UWABOR KING COLLINS
UWABOR KING COLLINS

Posted on • Updated on

Automation with Bash Script Pt 2.

In my previous update about my learning journey on day 7 of #120DAYSOFDEVOPS, I delved into the fascinating world of bash and automation. During that session, I emphasised the significance of bash scripting and discussed various aspects related to it. I even shared some insightful examples of simple bash scripts to demonstrate how to create them effectively. Now, as I move forward, my focus today will be on variables and conditionals ─ two fundamental concepts in bash that play a crucial role in file manipulation and overall script functionality.

Variables

Variables in scripting allow us to define and store recurring values or terms used within a potentially intricate script. To introduce a variable, you can simply assign it on a separate line in your script. For example:

Image description

If we now run oursh script you will see the printout that was added to our script.

Image description

We can also ask for user input that can set our variables using the following:

echo "Enter your name"
read name

Enter fullscreen mode Exit fullscreen mode

This would then define the input as the variable $name We could then use this later on.

Conditionals

In order to identify the participants in our challenge and track the number of days they have completed, we can utilise conditional statements such as if, if-else, and else-if. The script provided below demonstrates how we have implemented these conditionals.

# This script is to demonstrate a Script in Bash

# Defining the variable
 challengeName=120DaysOfDevOps
 totalDays=120

# User Input

echo "Enter your name"
read name

echo "Hello $name Welcome to $challengeName"
echo "This Challenge will last $totalDays days"
echo "Now how Many days have you spent in the challenge?"
read timeSpent

if [ $timeSpent -eq 120 ]
then
  echo "Outstanding! you have completed the 
  challenge."

elif [ $timeSpent -lt 120 ]
then
  echo "Keep pushing you are killing it!"

else
 echo "You have entered the wrong number of 
 days for the challenge."

fi
Enter fullscreen mode Exit fullscreen mode

Conditionals are an essential part of scripting and programming languages. They allow code to make decisions and execute different paths based on the evaluation of expressions. Bash and other languages provide various conditional operators to compare values:

  • eq: Checks if two values are equal
  • ne: Checks if two values are not equal
  • gt: Checks if the first value is greater than the second
  • ge: Checks if the first value is greater than or equal to the second
  • lt: Checks if the first value is less than the second
  • le: Checks if the first value is less than or equal to the second

These conditional expressions evaluate to True or False, allowing code to progress along the proper logical path.

Bash also provides file conditionals to evaluate attributes of files and directories:

  • -d: Checks if a file exists and is a directory
  • -e: Checks if a file exists
  • -f: Checks if a file exists and is a regular file
  • -g: Checks if the group id is set on a file
  • -r: Checks if a file is readable
  • -s: Checks if the file size is greater than 0

File conditionals are useful for writing scripts that interact with the filesystem. Overall, conditionals give programmers the ability to control program flow and make decisions.

FILE="120DaysOfDevOps.txt"
if [ -f "$FILE" ]
then
  echo "$FILE is a file"
else
  echo "$FILE is not a file"
fi
Enter fullscreen mode Exit fullscreen mode

Image description

In order to receive the first echo command, it is vital that the file remains in our directory. However, should we choose to remove the file,the second echo command will be returned instead.

Image description

Real World Job Scenario with Bash Automation Hands on.

Assuming I have a company called 120DaysOfDevOps Plc. and I want some jobs to be carried out by my DevOps engineer who happens to be one staff here is my letter to the staff and duties expected.

Dear Team,

I hope this message finds you well. As we continue to drive our company, 120DaysOfDevOps Plc, towards greater success, I want to take a moment to express my gratitude for your dedication and hard work.

In light of our growing needs, it has become evident that we must expand our team to ensure the smooth execution of various tasks related to DevOps. Currently, you, as our dedicated DevOps engineer, have been shouldering the responsibility for these critical functions.

To optimise efficiency and better utilise your skills, expertise, and time, we have decided to bring in additional professionals to support you. This strategic decision will enable us to handle the increasing workload effectively while maintaining the high standards we have set.

By redistributing responsibilities and streamlining workflows, we aim to create a more collaborative environment that encourages the exchange of knowledge and fosters professional growth.

As we proceed with this expansion, I assure you that your contributions remain invaluable to our organisation. Your expertise and insights will be crucial in training and guiding the new team members during their on-boarding process.

The program requirements are as follows:

  1. Accept a user input as a command line argument.
  2. Create a new user with the name provided as the command line argument.
  3. Parse and extract a password from the command line arguments.
  4. Set the extracted password for the created user.
  5. Display a success message indicating the successful creation of the user account.

Please note that these requirements outline the functionalities the program should possess in order to meet its objectives effectively.

Thank you for your commitment and unwavering dedication. If you have any questions or concerns, please do not hesitate to reach out to me. Let's embark on this exciting journey of growth together!

With warm regards,

Uwabor Collins
CEO/Director of Operations
120DaysOfDevOps Plc.

Solution

Let's begin by creating a shell script called "create_user.sh" using the "touch"
command. To make it executable, we can use the "chmod +x create_user.sh" command.

Next, we can open the script for editing using "vim/nano/or IDE to create_user.sh" command. In this script, we will address the first requirement, which is to allow a user to be passed in as a command line argument.

To achieve this, we can include the following code snippet in our script:

#!/bin/bash

# Check if a username is provided as a command line argument
if [ $# -eq 0 ]; then
    echo "Please provide a username as a command line argument."
    exit 1
fi

username=$1

# Rest of your script goes here...
Enter fullscreen mode Exit fullscreen mode

This code snippet checks if any command line arguments are provided when executing the script. If no arguments are given, it displays an error message

"Please provide a username as a command line argument." and exits. Otherwise, it assigns the provided username to the variable "username".

Image description

But in the situation where the username was not given it throws an error message.

Image description

To fulfill the second requirement of creating a user with the name provided as a command line argument, we can utilize the 'useradd' command. By including the '-m' option, the command will create the user's home directory at '/home/username'."

Image description

We can then check this account has been created with the awk -F: '{ print $1}' /etc/passwd | grep 'username' command.

Image description

Our next requirement is to explore the possibility of parsing a password as a command line argument. It's important to note that this is strictly for experimental purposes and will not be implemented in our production environment. By including this requirement, we aim to deepen our understanding of different approaches and techniques related to password handling in a controlled lab setting.

To illustrate the functionality of our script, let's consider an example. Suppose we run the script with the following parameters: ./create_user.sh 120DaysOfDevOps password. Upon executing this command, an image or screenshot (referenced as "the below image") can be provided to visually demonstrate the script's execution process. It will showcase that our script successfully creates a user account with the specified username and password. Furthermore, to verify the user creation, we manually switch to the newly created user and validate it using the whoami command. This visual representation helps us understand and confirm the successful execution of our script.

Image description

the output:

Image description

The final requirement is "A message of successful account creation is displayed." We already have this in the top line of our code and we can see on the above screenshot that we have a 120DaysOfDevOps user account being created shown. This was left from our testing with the $1 parameter.

Image description

Interactive console with user

Image description

One area for improvement that I noticed is our current method of displaying the password on the input. To address this, we can enhance security by utilising the "-s" flag in the code line read -s password. This modification ensures that the password remains hidden while it is being entered.

If you do want to delete the user you have created for lab purposes then you can do that withsudo userdel the various users like Stacey we created

Thanks for learning with me see you tomorrow

Top comments (0)