0% found this document useful (0 votes)
121 views18 pages

Bash Scripting Basic For Devops Beginners

Uploaded by

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

Bash Scripting Basic For Devops Beginners

Uploaded by

tobilobasam300
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

BASH SCRIPTING BASIC FOR DEVOPS (BEGINNERS)

Introduction: Bash, which stands for "Bourne Again Shell," is a widely used
command-line tool for Unix and Unix-like systems, such as Linux and macOS. It allows
users to interact with their operating system by typing text commands. Bash is
popular in DevOps for automating tasks, improving productivity, and maintaining
consistency in managing infrastructure.
Key Features of Bash Scripting
1. Easy to Learn: Bash scripting has a simple and straightforward syntax, making
it easy for both beginners and experienced developers to write automation
scripts.
2. Command-Line Power: Bash scripts can use the many command-line tools
available in Unix-like systems, making it easy to integrate with system
commands and utilities.
3. Text Processing: Bash is great at handling text, which is useful for tasks like
analyzing logs, extracting information, and manipulating text data.
4. Control Structures: Bash supports if-else statements, loops, and other control
structures, allowing you to create dynamic and flexible scripts.
Practical Uses of Bash in DevOps
1. Automating Deployments: Bash scripts can automate the process of
deploying applications, setting up environments, configuring files, and starting
services.
2. System Maintenance: DevOps engineers use Bash to configure system
settings, install software packages, and apply updates, ensuring consistency
across multiple servers.
3. Log Analysis: Bash is useful for reading and analyzing log files, helping with
monitoring and troubleshooting.
4. Scheduled Tasks: Bash scripts can be scheduled to run at specific times using
cron jobs, automating routine tasks like backups and log rotations.
5. Infrastructure as Code (IaaC): Bash scripts help manage infrastructure, often
working with tools like Ansible, Terraform, or Docker to configure, deploy, and
maintain systems.
6. Command-Line Proficiency: Being skilled in Bash allows you to efficiently
navigate and interact with Unix-based systems, which is essential for tasks like
debugging and system administration.
7. Task Automation: Bash can automate various tasks, such as parsing logs,
manipulating files, and processing data.
8. Troubleshooting: Bash is useful for writing quick scripts to diagnose and fix
problems, analyze logs, and check system configurations.
9. Customization: You can write custom Bash scripts to tailor your processes and
extend the functionality of existing tools.
10. Integration with DevOps Tools: Bash scripts can interact with various
DevOps tools and services, such as version control systems, CI/CD pipelines,
and monitoring tools.
11. Cross-Platform Compatibility: Bash scripts work on different Unix-
based systems, providing compatibility across platforms.
Best Practices for Bash Scripting in DevOps
1. Error Handling: Ensure your scripts handle errors gracefully and provide useful
feedback.
2. Documentation: Comment and document your scripts thoroughly to improve
maintainability and collaboration.
3. Security: Follow security best practices to avoid vulnerabilities like code
injection and unauthorized access.
4. Version Control: Use version control systems like Git to manage changes to
your scripts, facilitating collaboration and tracking.
5. Modularity: Modular programming involves breaking down a program into
smaller, independent modules (functions or classes). Each module focuses on a
specific task, making the code easier to understand, debug, and maintain.
By understanding and using Bash, you can automate tasks, streamline
operations, and improve efficiency in a DevOps environment.
As a DevOps engineer, you need to know how to give instructions to the
operating system and this method is what is called “scripting”. Here you write small
programs, called ‘scripts’, that automate repetitive tasks, manage system operations,
or perform specific functions within a software environment. These scripts are typically
written in scripting languages, which are designed to be easy to write and execute.
Here are the key points about scripting:
1. Automation:
 Scripts automate repetitive tasks, reducing manual effort and minimizing
errors.
 Commonly used in system administration, software development, and
data processing.
2. Scripting Languages:
 Scripting languages are typically high-level, easy-to-write languages.
 Examples include Bash, Python, Perl, Ruby, and JavaScript.
 They often require an interpreter to run, rather than being compiled into
machine code.
3. Command Execution:
 Scripts execute a series of commands to accomplish a task.
 Commands can include file operations, text processing, or running other
programs.
4. Ease of Use:
 Scripting languages are generally easier to learn and use compared to
full-fledged programming languages.
 They provide a straightforward way to write and run code quickly.
5. Flexibility and Integration:
 Scripts can interact with other software, tools, and systems.
 They are flexible and can be modified easily to adapt to different
requirements.
Practical Uses of Scripting
1. System Administration:
 Automate tasks like backups, updates, and system monitoring.
 Example: A script to update and upgrade all packages in a Linux system.
2. Web Development:
 Automate web-related tasks such as deploying websites, running servers,
or processing web forms.
 Example: JavaScript to validate user input in a web form.
3. Data Processing:
 Automate data analysis, manipulation, and reporting tasks.
 Example: A Python script to read data from a CSV file, process it, and
generate a report.
4. Software Development:
 Automate build processes, testing, and deployment.
 Example: A script to compile code, run tests, and deploy the application
to a server.
Why Use Scripting?
 Efficiency: Automates repetitive tasks, saving time and reducing errors.
 Productivity: Simplifies complex tasks and workflows, making them faster to
execute.
 Consistency: Ensures tasks are performed the same way every time, reducing
the risk of mistakes.
 Adaptability: Easy to modify and adapt scripts to changing requirements.
In a Linux/Unix system, there are several different types of shells that users can utilize.
Here are some of the most commonly used shells:
1. Bourne Shell (sh)
 The original Unix shell developed by Stephen Bourne.
 Standard shell on Unix systems.
 Output: /bin/sh
2. Bourne Again Shell (bash)
 An enhanced version of the Bourne Shell.
 Default shell on many Linux distributions.
 Includes features from the Korn shell (ksh) and C shell (csh).
 Output: /bin/bash
3. Korn Shell (ksh)
 Developed by David Korn.
 Compatible with the Bourne shell, but includes many enhancements.
 Identification of shell: /usr/bin/ksh
4. C Shell (csh)
 Developed by Bill Joy.
 Syntax resembles the C programming language.
 Includes features like history and job control.
 Identification of shell: /usr/bin/csh
5. TENEX C Shell (tcsh)
 An enhanced version of the C shell.
 Adds filename completion and command-line editing.
 Identification of shell: /usr/bin/tcsh
6. Z Shell (zsh)
 Includes features from bash, ksh, and tcsh.
 Highly customizable and supports many advanced features.
 Identification of shell: /bin/zsh
7. Almquist Shell (ash)
 A lightweight shell, often used in embedded systems.
 Compatible with the Bourne shell.
 Identification of shell: /bin/ash
8. Dash (Debian Almquist Shell)
 A modern replacement for ash.
 Lightweight and fast, often used as the default /bin/sh on Debian systems.
 Identification of shell: /bin/dash
9. Fish (Friendly Interactive Shell)
 Focuses on user-friendliness and interactive use.
 Includes features like syntax highlighting, autosuggestions, and a web-
based configuration interface.
 Indentification of shell: /usr/bin/fish
10. /bin/rbash
 Shell Name: Restricted Bash
 Description: A restricted version of Bash that limits certain capabilities
for security purposes.
11./usr/bin/tmux
 Tool Name: tmux
 Description: A terminal multiplexer, not a shell. It allows users to
manage multiple terminal sessions within a single window.
12./usr/bin/screen
 Tool Name: GNU Screen
 Description: Another terminal multiplexer, similar to tmux, used to
manage multiple terminal sessions.
Now let’s delve into the full class which is going to be hands-on

1. Understanding Concepts
Before diving into the hands-on exercises, let's briefly understand some key concepts.
 Variables: Placeholders for storing data that can be used and manipulated
within scripts.
 Inputs and Data Streams: Methods to accept input from the user or other
data sources and handle output.
 Conditional Statements: Statements that allow decision-making based on
certain conditions (if-else statements).
 Loops: Code structures that repeat a sequence of instructions until a specific
condition is met (for, while loops).
 Bash Functions: Reusable blocks of code that can be defined and called within
scripts.
Working with Variables
Every programming language should have what is called ‘variables’.
Variables helps in automating repitition of commands. A variable is a pointer to data in
memory. So anytime you want to store data in memory you use ‘variable’. So you say
a variables is a placeholder for data in memory- meaning that variables represent data
in memory.
In the computer, there are different storages. Variables are replacing you craming the
memory address. Variables arer easier to remember compared to memory address. So
for example if I want to store James inside the computer all I have to do is :
MyName=James. MyName is the variable.
So that means means that you set a variable by typing whatever you like and = to
store the data you want.
To output or call the variable or get the data stored in the variable you type: echo
$MyName.
In Bash, using quotes around strings is important for managing spaces and special
characters correctly. Here are the key points:
Single Quotes (')
 Purpose: Preserve the literal value of each character within the quotes.
 Usage: Use single quotes when the string contains special characters or spaces
that you do not want to be interpreted.
Example
echo 'Hello World'
echo 'Special characters like $ and * are preserved as literals'
Double Quotes (")
 Purpose: Preserve the literal value of most characters within the quotes, but
allow for variable expansion and command substitution.
 Usage: Use double quotes when you need to include spaces or special
characters, but also want to allow variable and command substitution.
Example
name="World"
echo "Hello $name"
echo "The date is $(date)"
No Quotes
 Purpose: Allow Bash to interpret special characters and split words based on
spaces.
 Usage: Use no quotes when you are sure the string contains no spaces or
special characters that need to be preserved.
Example
echo Hello
echo $USER
Practical Rules
1. No Spaces or Special Characters: You can omit quotes if the string contains
only alphanumeric characters without spaces or special characters.
echo HelloWorld
echo myfile.txt
2. With Spaces or Special Characters: Use quotes to prevent issues.
echo "Hello World" # Correct
echo Hello World # Incorrect, will print "Hello" and "World" on separate lines
3. Using Variables: Use double quotes to expand variables properly.
greeting="Hello World"
echo "$greeting" # Correct
echo $greeting # Correct, but not safe if greeting contains spaces or special
characters
Examples in Practice
Correct Usage
file="my file.txt"
echo "$file" # Correct, handles spaces

special='This is a test with $ and *'


echo "$special" # Correct, handles special characters

echo 'Literal $USER' # Correct, prints 'Literal $USER'


echo "Expanded $USER" # Correct, prints the value of the USER variable
Incorrect Usage
file=my file.txt
echo $file # Incorrect, will cause an error or unexpected behaviour
There are two types of variables in bash:
Environment Variables: In Bash, environment variables are special
variables that hold information about the environment in which Bash is running. They
are predefined by the system or set by the user and are accessible to all programs and
scripts running in that environment. These variables provide essential information to
programs, such as the current user's name, the system's architecture, or the location
of important directories.
 Example:
 HOME: Stores the path to the current user's home directory.
 PATH: Defines the directories in which executable files are located.
 USER: Holds the name of the currently logged-in user.
Declared/Custom Variables
In Bash, declared/custom variables are user-defined placeholders used to store
data or information. They are created by the user within a Bash script or session and
can hold various types of data, such as strings, numbers, or arrays. These variables
are assigned values using the = operator and can be accessed and manipulated
throughout the script or session.
 Example:
 name="John": Creates a variable named name and assigns it the value
"John".
 age=25: Creates a variable named age and assigns it the value 25.
 fruit="apple": Creates a variable named fruit and assigns it the value
"apple".
Usage in Bash Scripting
#!/bin/bash

# Environment Variable Example


echo "Your home directory is: $HOME"
echo "Your username is: $USER"

# Declared/Custom Variable Example


name="Alice"
age=30
echo "Hello, my name is $name and I am $age years old."
In the Bash script above:
 HOME and USER are environment variables provided by the system.
 name and age are custom variables declared within the script to store specific
data.
To see the list of environment variables on your system type : “env”
To get the environment variables but limit it to users type: “env | grep user
------------> To get only the environment variable name type: env | cut -d= -f1.
A variable cn be used to read, access and manipulate data throughout your script.
Example:
#!/bin/bash

# Declare variables
name="David"
age=25
city="Lagos"

# Print out the values stored


echo "Name: $name"
echo "Age: $age"
echo "City: $city"

# Perform operations with variables


birth_year=$((2023 - $age))
greeting="Hello, $name! You live in $city, and you were likely born in $birth_year."

# Display the final message


echo "$greeting"

VARIABLE NAMING CONVENTIONS


 Variable names should start with a letter or an underscore(_)
 Variable names can contain letters, numbers and underscores
 Variable names are CASE-sensitive
 Variable names should not contain spaces or special characters.
INPUT AND DATA STREAMS IN BASH

Are methods to accept input from the user or other data sources and handle output.
Basic Concepts
1. Standard Input (stdin): The default source of input for a program, typically
the keyboard.
2. Standard Output (stdout): The default destination for output from a program,
typically the terminal screen.
3. Standard Error (stderr): The default destination for error messages, typically
the terminal screen.
Redirection Operators
 >: Redirects stdout to a file (overwrites the file).
 >>: Redirects stdout to a file (appends to the file).
 2>: Redirects stderr to a file.
 <: Redirects stdin from a file.
Hands-On Examples
Redirecting Output to a File
1. Writing to a File
#!/bin/bash

# Write output to a file


echo "Hello, World!" > output.txt
 This script creates or overwrites output.txt with "Hello, World!".
2. Appending to a File
#!/bin/bash

# Append output to a file


echo "Another line" >> output.txt
 This script appends "Another line" to output.txt.
Redirecting Error Messages
1. Redirecting stderr to a File
#!/bin/bash

# Redirect error message to a file


ls non_existing_file 2> error.log
 This script attempts to list a non-existing file, and the error message is
redirected to error.log.
Using stdin from a File
1. Reading from a File
#!/bin/bash

# Read from a file


file=”names.txt”
while read -r line;
do
echo "Read line: $line"
done < “$file
You must have created a file called names.txt
 This script reads each line from input.txt and echoes it.
Using read for User Input
1. Prompting for User Input
#!/bin/bash

# Prompt for user input


echo "Enter your name:"
read name
echo "Hello, $name!"
 This script prompts the user to enter their name and then greets them.
Piping Data Between Commands
1. Using Pipes (|)
#!/bin/bash

# Pipe data between commands


ls -l | grep ".sh"
 This script lists all files and directories in long format, then filters the output to
show only files with .sh extension.
CONDITIONAL STATEMENTS IN BASH
Conditional statements in Bash are used to perform different actions based
on different conditions. They allow you to control the flow of your script by executing
certain commands only if specific conditions are met.
In Bash scripting there are two types of conditional statements:
 If
 Else
 The third is elif
The ‘if’ syntax execute a command(s) as long as the condition is TRUE.
The ‘else’ syntax execute a command(s) as long as the condition is FALSE or if none
of the listed conditions are TRUE.
The ‘elif’ syntax execute a command(s) as long as another_condition is TRUE.
Examples format:
if [ condition ]; then
# commands to execute if condition is true
elif [ another_condition ]; then
# commands to execute if another_condition is true
else
# commands to execute if none of the above conditions are true
fi
HANDS-ON EXAMPLES
Basic ‘if’ statement:
#!/bin/bash

# Prompt for user input


echo "Enter your age:"
read age

# Conditional statement to check age


if [ "$age" -eq 18 ]; then
echo "You are an adult."
fi

This script checks if the user's age is 18 or older and prints a message accordingly.
Basic ‘else’ statement:
#!/bin/bash
age=12
if [ $age == “James” ]
then
echo “Positive”
else
echo “This is the wrong user”
fi

Basic ‘elif’ statement:


#!/bin/bash

# Prompt for user input


echo "Enter a number:"
read number

# Conditional statement to check the number


if [ "$number" -gt 0 ]; then
echo "The number is positive."
elif [ "$number" -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
This script checks if a number is positive, negative, or zero and prints a message
accordingly.
Other examples:
#!/bin/bash

# Prompt for user input


echo "Enter a number between 1 and 10:"
read number

# Conditional statement using logical AND


if [ "$number" -ge 1 ] && [ "$number" -le 10 ]; then
echo "The number is within the range."
else
echo "The number is out of range."
fi
This script checks if a number is between 1 and 10 using a logical AND operator.
#!/bin/bash

# Prompt for user input


echo "Enter your username:"
read username

# Conditional statement to check username


if [ "$username" = "admin" ]; then
echo "Welcome, admin!"
else
echo "Welcome, $username!"
fi
This script checks if the entered username is "admin" and prints a special welcome
message.
Here's a comprehensive example that uses conditional statements to create a simple
number guessing game:
#!/bin/bash
# Generate a random number between 1 and 10
target=$(( RANDOM % 10 + 1 ))

# Prompt the user to guess the number


echo "Guess the number between 1 and 10:"
read guess

# Conditional statements to check the guess


if [ "$guess" -eq "$target" ]; then
echo "Congratulations! You guessed the correct number."
elif [ "$guess" -lt "$target" ]; then
echo "Too low! The correct number was $target."
else
echo "Too high! The correct number was $target."
fi
This script generates a random number between 1 and 10, prompts the user to guess
the number, and uses conditional statements to check if the guess is correct, too low,
or too high.
OPERATORS FOR CONDITONALS IN BASH SCRIPTING
The are two operators for conditionals in bash:
 -f: This operator is used to check if a file exists and is a regular file (not a
directory or a special file like a device node).
 -d: This operator is used to check if a directory exists.
Examples:
Checking if a File Exists:
#!/bin/bash

file="example.txt"

if [ -f "$file" ]; then
echo "File $file exists and is a regular file."
else
echo "File $file does not exist or is not a regular file."
fi
Checking if a Directory Exists:
#!/bin/bash

directory="example_directory"
if [ -d "$directory" ]; then
echo "Directory $directory exists."
else
echo "Directory $directory does not exist."
fi
Other examples:
For files
#!/bin/bash
if [ -f "images.png" ]; then # Check if "images.png" exists and is a regular
file
echo "The images folder exists already moving on..." # Print message if it
exists
sleep 0.5 # Sleep for 0.5 seconds
else # If "images.png" doesn't exist
touch "images.png" # Create an empty file named "images.png"
fi
For Directory
#!/bin/bash
if [ -d "images" ]; then # Check if "images" directory exists
echo "The images directory exists already, moving on..." # Print message
if it exists
sleep 0.5 # Sleep for 0.5 seconds
else # If "images" directory doesn't exist
mkdir "images" # Create the "images" directory
fi
LOOPS IN BASH SCRIPTING
Loops in bash scripting allows you to execute a set of commands repeatedly until the
command is carried out completely. Loops in Bash allow you to execute a block of code
repeatedly based on a condition. There are mainly three types of loops in Bash:
1. for loop: Executes a sequence of commands for each item in a list or range. It
goes through a set of items, elements or range of value.
2. while loop: Executes a sequence of commands as long as a condition is true. It
continues to run a particular condition until has changed.
3. until loop: Executes a sequence of commands until a condition becomes true.
You can use various commands within loops such as ‘read’ and ‘test’ commands in
bash scripting.
The ‘test’ command use [], while the read command uses ‘read’ within the loop in
bash scripting.
Examples:
1. for Loop:
#!/bin/bash
for fruit in apple banana cherry; do
echo "I like $fruit"
done
 In this example, the echo command is used within the for loop to print
each fruit.
2. while Loop:
#!/bin/bash
counter=1
while [ $counter -le 5 ]; do
echo "Count: $counter"
counter=$((counter + 1))
done
 Here, the echo command is used within the while loop to print the count.
3. until Loop:
#!/bin/bash
counter=1
until [ $counter -gt 5 ]; do
echo "Count: $counter"
counter=$((counter + 1))
COMPARISON OPERATORS IN LOOPS
String Comparison:
 ==: Equal to
 !=: Not equal to
 Numeric Comparison:
 -eq: Equal to
 -ne: Not equal to
 -lt: Less than
 -le: Less than or equal to
 -gt: Greater than
 -ge: Greater than or equal to
Logical Operators
 &&: Logical AND
 ||: Logical OR
 !: Logical NOT
Examples:
‘for’ Loop with String Comparison:
#!/bin/bash

# List of fruits
fruits=("apple" "banana" "cherry")
# Loop through each fruit
for fruit in "${fruits[@]}"; do
if [ "$fruit" == "banana" ]; then
echo "Found a banana!"
else
echo "This is a $fruit."
fi
done
‘while’ Loop with Numeric Comparison
#!/bin/bash

# Initialize a counter
counter=1

# Loop until the counter is greater than 5


while [ $counter -le 5 ]; do
echo "Counter is $counter"
counter=$((counter + 1)) # Increment the counter
done

1. Logical AND (&&) in a for Loop:


#!/bin/bash

# Iterate through a list of numbers and print only even numbers


for (( i=1; i<=10; i++ )); do
(( i % 2 == 0 )) && echo "$i is even"
done
 This for loop iterates from 1 to 10 and checks if each number is even. If a
number is even (i % 2 == 0), it prints a message.
2. Logical OR (||) in a for Loop:
#!/bin/bash

# Iterate through a list of filenames and echo a message if the file exists or
is readable
for file in file1.txt file2.txt file3.txt; do
[ -e "$file" ] || echo "$file does not exist"
done
 This for loop iterates through a list of filenames and checks if each file exists. If
a file does not exist (-e), it echoes a message.
3. Logical NOT (!) in a for Loop:
#!/bin/bash

# Iterate through a list of numbers and print only odd numbers


for (( i=1; i<=10; i++ )); do
! (( i % 2 == 0 )) && echo "$i is odd"
done
 This for loop iterates from 1 to 10 and checks if each number is odd by negating
the condition (!). If a number is odd, it prints a message.
To ‘iterate’ means to repeat a proces multiple times, usually involving going through
a sequence of elements, performing a series of instructions, or executing a set of
condition is ‘true’.
FUNCTIONS IN BASH SCRIPTING
A function is a body or block of code that contains processes or commands that
can be repeated or are reuseable and they are called within scripts. All programming
languages has functions. Functions in Bash allow you to group commands together
and execute them as a single unit. This can help make your scripts more organized,
reusable, and easier to understand.
Functions must have a single purpose or do only one thing.
In coding there’s a concept of ‘DRY’ which means ‘Don’t Repeat Yourself’.
So function has lines of codes written to carry out just one responsibility/task.
STEPS TO USING FUNCTIONS
 Functions creation or definition: To call a function in bash, use its name
followed by parentheses and curly braces, the commands and closing curly
braces..
Example:
# Define a function
#!/bin/bash
greet() {
echo "Hello, welcome to Bash scripting!""
}
 Functions calling or invocation: Functions invocation is output. The greet
function is called by simply writing its name: ‘greet’
Full example of function:
#!/bin/bash
# Define a function
greet() {
echo "Hello, welcome to Bash scripting!"
}
# Call the function
greet
In function we have what we call ‘global and local variable’.
A ‘global variable’ is defined outside the function itself. A ‘local variable’ is defined
in the function itself.
Examples:
username=james
list_inventory(){
echo " Welcome to Directory Creator
................................................................
by Must Mika"
local username=john
echo $username
}
list_inventory
echo $username
In functions for bash to give people an option to input things we use ‘read -p’ and
make it readable.

Example:
list_inventory(){
echo " Welcome to Directory Creator
-------------------------------
by Yusuf Clust"

read -p "Enter the name of the inventory file: " inventory_name

echo $inventory_name

if [[ ! -f $inventory_name ]]
then
echo "File does not exist"
exit 1
else
while read -r line
do
echo $line
done < $inventory_name

fi

list_inventory
echo $username

In function we have ‘Argument’ and ‘parameters’. ‘Argument’ are data passed in


the function invocation. ‘Parameters’ are passed as data inside the function itself. It
is represented by $and numbers. $1 represents the first argument and the
likes. $0 represents the function itself.
Example:
greet() {
echo "Hello, $1 Today is $2."
}

greet "Alice" "Monday" ## This is to call greet function with two arguments

In Bash Scripting the ‘exit’ command is used to exit a script or a function. The
argument to exit is a numeric value called an ‘exit status’. Conventionally, a script or
function returning ‘0’ indicates success and any other value indicates an error or
some kind of failure.
‘exit 1’ is often used to indicate error or failure condition. So if ‘exit 1’ is
returned it means something went wrong within the function and the script should exit
with a non-zero status to signal an error to the calling environment.
‘$?’ checks the exit status for the last executed command or function.
‘$#’ is used to get the number of argument that the function receives.

You might also like