Shell Scripting with Bash (Part-1)

Scripts are nothing but the set of commands mentioned in sequence and stored in a file with or without some logics. Most of the modern Linux distributions come with Bash as a default shell. This shell has capability to perform logical operation which is used to create script.

If you are a System administrators and having time consuming tasks daily then you can use shell scripts to automate routine tasks.

Structure of a Shell Script

As Linux comes with more than one shell, it is compulsory to mention in a script which shell you are going to use and that is known as interpreter and need to be mentioned in first line in a shell script.

For ‘Bash’ shell:

#!/bin/bash

For ‘SH’ shell:

#!/bin/sh

This line also called as “Shebang”.

Although there is no rule to create shell/Bash script if you are just creating a set of commands but if you are creating a script with conditional and logical operation, in that case you must follow some basic structure to make you script more reliable.

Very first section we will include is Header:

Header:

In header we can mentioned

  • Purpose of the script

  • Author of script

  • Revision number if required

  • Date of creation

  • Description/Instructions to run the script

The above mentioned lines must not be executed by shell as shell will not understand and will through an error. So to instruct shell to ignore these lines we can comment-out them.

Shell does not execute blank line and commented lines. To comment out a line, simply place a “#” sign at the beginning of line.

We can create a Header as below:


#=========================================================
# SCRIPT NAME: myfirstscript.sh
# PURPOSE: Demo
# REVISION HISTORY: 1
# AUTHOR      DATE    DETAILS
# --------------------- --------------- --------------------------------
# My Name  10-08-2020   creating first script
#=========================================================
 

After mentioning the above details, the next part is the Variable definition.

In almost every programmatic language it is suggested to mention variable first.

But in bash scripting it is not compulsory to mention variable in the beginning of script but it is necessary to define variable before using it. You can define variable anywhere in bash script.

But for making script more readable and understandable, it is being advised to mention it at the beginning.

Variables:

Like other programming languages, variables are used to store the data/values.

In Bash also you can store values in variables; you can also store the output of command in a variable. You can define as number of variables as you want.

Variables are used to store the fixed values but those values can be over written.

Single quotes (‘ ‘), double quotes (“ “), back quotes (` `) or dollar ($) is used to define the variable values.

Variables must be Upper case but not compulsory, if you are using lowercase variable and by any change or by mistake you define it similar to system defined variables then your script will not work properly or may break something.

For example:

If you have to define the variable for hostname and you define it like:


hostname=’myhost’ 

This may create confusion in script and your script may print the output as ‘yourhostname’ instead of ‘myhost’

Syntax would be:


#shabang
Headers
Variables 
e.g:- HOST=$(hostname –f)

One thing to mentioned here is that, you can use “$” symbol to retrieve your variable value.

i.e:

$HOST

OR

${HOST}


Body:

The next action is Body, here we define the structure of script we bestdefine conditional operations, logical operations and we used to print output on the screen in the body section.

In body section we define the sequence of commands line, we can directly run the command or we can use variables to store the value and print that value by using Dollar symbol in body section.

Now the sequence would be:

#Shabang
#Headers
Variables
Body

For Example:

echo "This is my First Script"
 
# ASSIGN VARIABLES
 
HOST=$(hostname -f) #storing   hostname in a variable
 
# SHOW MESSAGES
 
echo "Hostname: ${HOST}"  #using {} for best practices

I will create a file and put everything together (shabang, header, variables and body) and save as myscript.sh.

“.sh” is the extension for shell script.

Now, to run the script, I run it as:

user@host:/$ /bin/sh myscript.sh

or

user@host:/$sh myscript.sh

Also

user@host:/$/bin/bash myscript.sh

or

user@host:/$ /bash myscript.sh

I can also run as:

user@host:/$ ./myscrpt.sh

This will call interpreter that the command is going to run the script.

But, before running the above command, we need to provide the executable permission to script.

To provide executable permission;

chmod a+x myscript.sh

or

chmod 755 myscript.sh

user@host:/$ ./myscript.sh
This is   my First Script
Hostname:   Khalid-System.localdomain

As you can see in the above, script has stored the value of hostname and echo is used to print it’s value on screen.


Conditional Statements:

Bash provides the very basic and strong conditional statement expression.

When you need to execute the commands depending on a condition, you can use if/elif/else/fi.

Bash uses the pseud-code for the syntax to put conditional statement.

Please note that there must be a space before and after the opening and closing bracket:

if [ condition 1 ]

then

commands

else

commands

fi

You might be having multiple conditions in a loop, you can use them as:

if [ condition 1 ]

then

commands

else

if [ condition 2 ]

commands

else

commands

fi

fi

Similar scenario can also be achieve with elif as:

if [ condition 1 ]

then

commands

elif [ condition 2 ]

commands

else

commands

fi

From our previous script, just putting simple condition.



OutPut:



As you can see in output, there are three lines .

First is our first echo statement.

Second is from the condition as it is failed.

Third is our last echo to show the right hostname of system.

Let’s have the another example of simple script with nested if-else (if-elif-else-fi).



I hope you can easy understand this script now.

Next is Loops which we will see in next part...


96 views0 comments

Recent Posts

See All

TCP-Route.com

Pune, Maharashtra, India

©2020 by Khalid Waseem.