0% found this document useful (0 votes)
4 views42 pages

Shell-Scripting-Devops - Module 3

The document provides an overview of shell scripting within the context of DevOps, detailing key concepts such as the Linux shell, bash, shell variables, flow controls, loops, functions, lists, string manipulation, file reading and writing, and positional parameters. It emphasizes the importance of shell scripting for task automation, customization, and efficient file management. Additionally, it includes examples and syntax for various scripting components to aid understanding.

Uploaded by

Shwetha T.h
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views42 pages

Shell-Scripting-Devops - Module 3

The document provides an overview of shell scripting within the context of DevOps, detailing key concepts such as the Linux shell, bash, shell variables, flow controls, loops, functions, lists, string manipulation, file reading and writing, and positional parameters. It emphasizes the importance of shell scripting for task automation, customization, and efficient file management. Additionally, it includes examples and syntax for various scripting components to aid understanding.

Uploaded by

Shwetha T.h
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DevOps

Department of
Master of Computer Applications

[Link]
DevOps

23MCA593

By
Module - 3 SHWETHA T H
Assistant Professor
Dept. of MCA
Citech-Bengaluru.

Prof. Shwetha T H, MCA, Citech


Shell Scripting

Department of Master of Computer Applications [Link]


Introduction to Linux shell
scripting
• If we are using any major operating system, we are
indirectly interacting with the shell.
• While running Ubuntu, Linux Mint, or any other
Linux distribution, we are interacting with the shell
by using the terminal.
• Before understanding shell scripting we have to get
familiar with the following terminologies:
• Kernel, Shell, Terminal, etc.,

Department of Master of Computer Applications [Link]


some common uses of Shell
Script:
• Task Automation
It can be used to automate repetitive tasks like regular
backups and software installation tasks.
• Customization
One can use shell scripts to design its command line
environment and easily perform its task as per needs.
• File Management
The shell scripts can also be used to manage and
manipulate files and directories, such as moving,
copying, renaming, or deleting files.

Department of Master of Computer Applications [Link]


What is bash

• Bash, short for Bourne Again Shell, is an open-source


command-line shell interpreter and scripting
language. It interprets user-entered commands, either
interactively or from a script file.
• It serves as an interface to call commands, enabling
system function calls.

Department of Master of Computer Applications [Link]


What is bash

There are two types of bash modes


1. Interactive mode:
Also called a command interpreter, it allows the
execution of commands in the terminal. It executes
commands sequentially if there are multiple
commands.
2. Non-interactive mode:
This refers to scripts, allowing you to write Bash syntax
that contains a sequence of multiple commands for
script execution.

Department of Master of Computer Applications [Link]


Shell Variables
• A shell variable is a character string in a shell that
stores some value. It could be an integer, filename,
string, or some shell command itself.
• Basically, it is a pointer to the actual data stored in
memory. We have a few rules that have to be
followed while writing variables in the script (which
will be discussed in the article).
• Overall knowing the shell variable scripting leads us
to write strong and good shell scripts.

Department of Master of Computer Applications [Link]


Shell Variables
Rules for variable definition
• A variable name could contain any alphabet (a-z, A-
Z), any digits (0-9), and an underscore ( _ ).
• However, a variable name must start with an
alphabet or underscore.
• It can never start with a number.

Department of Master of Computer Applications [Link]


Shell Variables
Following are some examples of valid and invalid
variable names:

Valid Variable names:


ABC
_AV_3
AV23

InValid Variable names:


2_a
!AB
$ABC
&%OP
Department of Master of Computer Applications [Link]
Flow Controls
A programming language, even a simple one, requires the
ability to change its functionality depending upon certain
conditions. For example, if a particular file exists or if the
number represented by a variable is greater than some
value then perform some action, otherwise perform a
different action.
Some of the flow controls/Conditional statements:
• if statement
• if-else statement
• if..elif..else..if statement (Else If ladder)
• if..then..else..if..then..fi..fi..(Nested if)
• switch statement
Flow Controls
1. if statement: if statement used to test the validity of an
expression.
This block will process if specified condition is true.
Syntax:

Example:
Flow Controls
2. if-else statement: If specified condition is not true in if part
then else part will be execute.
Syntax: Example:
Flow Controls
Example 2: if statement
Flow Controls
3. if..elif..else..if statement (Else If ladder):
• To use multiple conditions in one if-else block, then
elif keyword is used in shell.
• If expression1 is true then it executes statement 1
and 2, and this process continues.
• If none of the condition is true then it processes else
part.
Flow Controls
Syntax: Example:
Flow Controls
4. if..then..else..if..then..fi..fi..(Nested if)
• Nested if-else block can be used when, one condition
is satisfies then it again checks another condition.
• In the syntax, if expression1 is false then it processes
else part, and again expression2 will be check.
Flow Controls
Syntax: Example:
if [ 0 -eq 1 ]
then
echo “0=1”
else
if [ 0 -eq 2 ]
then
echo “0=2”
else
echo “0!=2”
fi
fi
Flow Controls
5. switch statement
• case statement works as a switch statement if specified
value match with the pattern then it will execute a block
of that particular pattern
• When a match is found all of the associated statements
until the double semicolon (;;) is executed.
• A case will be terminated when the last command is
executed.
• If there is no match, the exit status of the case is zero.
Flow Controls
Syntax:

Example: CARS="bmw"

#Pass the variable in string


case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach, Germany" ;;

#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;

#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
esac
Loops
Looping Statements in Shell Scripting: There are total 3
looping statements that can be used in bash
programming
• `while` statement in Shell Script in Linux
• `for` statement in Shell Script in Linux
• `until` statement in Shell Script in Linux

To alter the flow of loop statements, two commands are


used they are,
break
continue
Department of Master of Computer Applications [Link]
Loops
1. `while` statement in Shell Script in Linux
Here the command is evaluated and based on the
resulting loop will execute, if the command is raised to
false then the loop will be terminated that.

Department of Master of Computer Applications [Link]


Loops
2. `for` statement in Shell Script in Linux
The for loop operates on lists of items. It repeats a set of
commands for every item in a list.
Syntax with example:

Department of Master of Computer Applications [Link]


Loops
3. `until` statement in Shell Script in Linux
The until loop is executed as many times as the
condition/command evaluates to false. The loop
terminates when the condition becomes true.

Department of Master of Computer Applications [Link]


Functions
Function
A function is a collection of statements that execute a
specified task. Its main goal is to break down a complicated
procedure into simpler subroutines that can subsequently be
used to accomplish the more complex routine.
For the following reasons, functions are popular:
• Assist with code reuse.
• Enhance the program’s readability.
• Modularize the software.
• Allow for easy maintenance.

Department of Master of Computer Applications [Link]


Functions
The basic structure of a function in shell scripting looks
as follows:

Department of Master of Computer Applications [Link]


Lists
In Bash, there is no data type named “list”, but you can
generate a list using bash scripts that you can use for
your needs. Also, sometimes associative arrays are
referred to as lists in Bash scripting. In this article, I will
demonstrate how to create a list in Bash scripts and give
some examples.
2 Methods to Create List Using Bash Scripts
Method 1: Create a List Using Loops in Bash Scripts
Method 2: Create a List Using Arrays in Bash Scripts

Department of Master of Computer Applications [Link]


Lists
Methods to Create List Using Bash Scripts
Method 1: Create a List Using Loops in Bash Scripts
Case 1: Generate List Using "for" Loop in Bash Script
Suppose, I want to list files with “employee” in the name. To
do so I’ve used for loop to go through the files in loops. If you
want to achieve this, please check & execute the following
Bash script:

Department of Master of Computer Applications [Link]


Lists
Case 2: Generate List Using "while" Loop in Bash Script
In this case, I will show you how to generate a list of numbers
using a while loop. Also, to make this script more interactive,
the list of numbers will take user input. So, you can get the list
of numbers according to your choice.
To list numbers with a while loop, see the below bash script:

Department of Master of Computer Applications [Link]


Lists
Method 2: Create a List Using Arrays in Bash Scripts
In this method, I have demonstrated the process
of generating any list using an array. I have generated a list
of months. Moreover, you can use the array to generate any
list you want, you just have to change the list's contents.
To list the names of months using arrays, go through the
following bash script:

Department of Master of Computer Applications [Link]


Manipulating Strings
String Manipulation is defined as performing several
operations on a string resulting change in its contents. In
Shell Scripting, this can be done in two ways: pure bash
string manipulation, and string manipulation via external
commands.
Basics of pure bash string manipulation:
• Assigning content to a variable and printing its content:
• To print length of string inside Bash Shell
• Concatenate strings inside Bash Shell using variables
• Concatenate strings inside Bash Shell using an array
• Extract a substring from a string

Department of Master of Computer Applications [Link]


Manipulating Strings
Basics of pure bash string manipulation:
1. Assigning content to a variable and printing its content:
Syntax: Example:

Department of Master of Computer Applications [Link]


Manipulating Strings
Basics of pure bash string manipulation:
2. To print length of string inside Bash Shell
Syntax: Example:

Department of Master of Computer Applications [Link]


Manipulating Strings
Basics of pure bash string manipulation:
3. Concatenate strings inside Bash Shell using variables
Syntax: Example:

Department of Master of Computer Applications [Link]


Manipulating Strings
Basics of pure bash string manipulation:
4. Concatenate strings inside Bash Shell using an array
Syntax: Example:

Department of Master of Computer Applications [Link]


Manipulating Strings
Basics of pure bash string manipulation:
5. Extract a substring from a string
Syntax:

Example:

Department of Master of Computer Applications [Link]


Reading and Writing Files
Reading Files
Reading a file is a process that involves the access of read and
manipulation of its content. It is important to read files in
bash for automation, scripting, error handling and validation,
and configuration files. There are various ways in which a file
can be read in bash depending on specific criteria of files. In
Linux, we have shell scripting that can do it with just a few
lines.

Department of Master of Computer Applications [Link]


Reading and Writing Files
Writing Files
Writing to a file is important to store info for further analysis.
Using Bash script one can easily write command output, error
and generate reports or logs of a completed task. There are
multiple ways to write in a file using Bash script. In this
article, I will show you simple but effective methods to write
and append data to a file.

Department of Master of Computer Applications [Link]


Positional Parameters

• Positional parameters are a fundamental concept in


shell scripting, providing a way to pass arguments to a
script or function.
• They enable customization, interactivity, and flexibility
in scripts, allowing you to create versatile and
powerful command-line utilities.
• With the example, we will explore what positional
parameters are, how they work, and their practical
applications in shell scripting.

Department of Master of Computer Applications [Link]


Positional Parameters
Accessing Positional Parameters
• In shell scripting you can access positional
parameters using special variables, such
as $1, $2, $3, and so on.
• These variables represent the values of the
arguments passed to the script with $1 representing
the first argument, $2 the second, and so forth.

Department of Master of Computer Applications [Link]


Positional Parameters
For example, consider a simple shell script
named [Link] that takes two positional parameters
and displays them:
echo "The first argument is: $1"
echo "The second argument is: $2"

When you run the script with two arguments:


$ bash [Link] argument1 argument2

The script will output:


The first argument is: argument1
The second argument is: argument2
Department of Master of Computer Applications [Link]
Prof. Shwetha T H, MCA, CIT

You might also like