How To Use Bash Scripting For Automating A Task

Reading Time: 5 minutes

Introduction

Bash scripting is a convenient way to automate things on any Linux system, and we’re going to use it here to automate certain tasks we use all the time.

Bash is a simple language for stringing together several different Linux utilities. Its simplicity makes it easy for beginners to create lots of scripts that would otherwise be pretty complicated or require some pretty hefty programming skills. Bash (AKA Bourne Again Shell) is a type of interpreter that processes shell commands. A shell interpreter takes commands in plain text format and calls Operating System services to do something. For example, the ls command lists the files and folders in a directory.

Understanding shell scripts

Basically, a shell script is a program that includes different commands and instructions. These commands as well as instructions perform tasks, one by one, when run individually. But there are certain things that we do, for which we need to write commands very frequently. This is really time-consuming; therefore, we write a program to collectively run these commands and automate tasks.

Another important thing about these programs is that, unlike others, they are not compiled but interpreted. This means that when running the program, a child shell is created. All the operations are performed in that shell, and this child shell terminates itself after the completion of all the tasks in the program.

Best practices for writing effective scripts

Shell scripting, though very simple, is a very effective method for creating easy, small but effective programs. However, to write an efficient format of code script, one needs to take care of certain things in order to ensure better administration, management, and debugging of the code, if needed.

Here are some points to be pondered while writing a shell script:

  • Write comments in the code wherever necessary. This helps others also to understand the working mechanism of the code much more easily.
  • Try to exit the script as soon as any error is encountered within it, as even the smallest error bug can do great damage to your system.
  • Use the functions you can write by yourself in the script, as it is much easier to call it and debug it.
  • Using the $ sign is recommended, in place of single quotes (‘’) as it helps us to differentiate between the process of substitution and the declaration of commands.

The advantages and disadvantages of shell scripting

Advantages

  • A special feature is that the user can easily run multiple commands together in a single line command.
  • The commands are easy to write and execute, and are used in many automated systems.
  • Previously executed operations can also be rewound, and the functions and commands can be performed automatically.
  • Supports almost every system that has a UNIX based architecture and hence is portable from one system to another.

Disadvantages

  • The execution time is longer as it is not specifically a programming language but a command line script.
  • A new thread or mini process is created for each command executed in the shell script.

Steps To Write Bash Script

1. Find You Bash Interpreter

To get started, we need to know which Bash interpreter we’re using. To do so, use which bash in a terminal window. Learning the location of the interpreter will be useful when writing our first Bash script.

2. Make Your First Bash Script

To start a new Bash script, create and open a new Bash file called “bash.sh”

~# nano bash.sh

start the first line with a shebang (#!) followed by the location of your Bash interpreter (for me, it’s usr/bin/bash). When the program is opened, this will tell it how to interpret the language we’re writing the rest of the script in.

#! /usr/bin/bash

Let’s create a variable to make something happen. For something simple, we’ll just use a S that says GOOD MORNING. You could make it say whatever you want.

S="AS ALWAYS"

Now we want to echo something back. In our example, we’ll echo “I LOVE MY INDIA” where $ indicates a call to a variable, in this case, STRING. What this will do is print the message, swapping out $STRING for whatever your STRING is.

echo "I LOVE MY INDIA $S"

Here’s what the script should look like as a whole:

#! /usr/bin/bash
S="AS ALWAYS"
echo "I LOVE MY INDIA $S"

Save your script by hitting Control-X on your keyboard to exit, then Y to save the modified buffer, and then Enter to save the file. This will bring you back to the terminal window. To test out the script, use bash bash.sh (or whatever you named it) to call the script. You should see the echoed message appear. Success!

~# bash bash.sh

I love my India as always

Automating user management with bash script

Creating a user on multiple servers may be something that you would do on a daily basis as a sysadmin. It is a tedious task, and so let’s create a bash script that automates it.

First, create a text file that includes all the server host names or IP addresses where you wish to add the user on.

For example, here I created the file servers.txt that includes five different servers:

knoldus@knoldus-Vostro-3590~$ cat servers.txt
server1
server2
server3
server4
server5

Keep in mind, that I have used server hostnames as I have already included the IP addresses in my /etc/hosts file. You can also use the SSH config file here.

Now take a look at the following adduser.sh bash script:

#!/bin/bash

servers=$(cat servers.txt)

echo -n "Enter the username: "
read name
echo -n "Enter the user id: "
read uid

for i in $servers; do
echo $i
ssh $i "sudo useradd -m -u $uid ansible"
if [ $? -eq 0 ]; then
echo "User $name added on $i"
else
echo "Error on $i"
fi
done

The adduser.sh script would first ask you to enter the username and the user id of the user who you want to add; then, it will loop over and connect to all the servers in the servers.txt file via SSH and add the requested user.

The script ran successfully and user ansible was added on all five servers. There are a couple of important points here you need to understand:

  • You can either use empty ssh pass phrases or run ssh-agent to avoid getting prompted to enter a key (or password) while the script is running.
  • You must have a valid account that has super user access (without a password requirement) on all the servers.

Imagine that you need to add a user on 100+ different Linux servers! The adduser.sh script can definitely save you countless hours of work.

Conclusion

This Blog didn’t get very far with creating a shell script, but it did create a very small one. It also explored the reasons for creating shell scripts and why they are the most efficient option for the system administrator (rather than compiled programs).

Reference

Example

Written by 

Deeksha Tripathi is a Software Intern at Knoldus Inc Software. She has a keen interest toward learning new technologies. Her practice area is Devops. When not working, she will be busy in listening music , and spending time with her family .

Leave a Reply