Bash Scripting for DevOps Engineers
Bash Scripting for DevOps Engineers
Bash (Bourne Again Shell) is one of the most essential scripting languages for DevOps engineers.
It is used for automating system administration tasks, managing cloud infrastructure, creating
CI/CD pipelines, and handling configuration management.
Bash scripting is a way of automating command-line tasks in Unix-based operating systems like
Linux and macOS. A Bash script is simply a text file containing a series of commands that are
executed sequentially by the shell.
Bash scripting is a fundamental skill for DevOps engineers for the following reasons:
Writing Bash scripts to automate code building, testing, and deployment in Jenkins, GitHub
Actions, and GitLab CI/CD. Example: A script that triggers deployment when code is pushed to
GitHub.
Automating AWS, Azure, and GCP services using CLI tools inside Bash scripts.
Example: A script that provisions AWS EC2 instances using AWS CLI.
Writing Bash scripts to monitor system logs and send alerts when issues arise.
Example: A script that scans logs for error messages and emails the DevOps team.
nano myscript.sh
or
vim myscript.sh
#!/bin/bash
chmod +x myscript.sh
./myscript.sh
Output:
1. Variables in Bash
#!/bin/bash
name="DevOps Engineer"
Output:
#!/bin/bash
read user_name
#!/bin/bash
read num
else
fi
4. Loops in Bash
For Loop
#!/bin/bash
for i in {1..5}; do
done
While Loop
#!/bin/bash
count=1
((count++))
done
#!/bin/bash
#!/bin/bash
backup_dir="/backup"
mkdir -p $backup_dir
cp -r /var/log/* $backup_dir
#!/bin/bash
threshold=80
fi
#!/bin/bash
#!/bin/bash
fi
7. Conclusion
Bash scripting is an essential skill for any DevOps engineer. It enables automation of system
administration, CI/CD pipelines, cloud management, and monitoring tasks.
Learning Bash scripting will significantly enhance your efficiency in handling Linux-based DevOps
workflows.
Types of scripts:
1. Bash
2. Zsh - Z Shell
5. Csh - C Shell
7. PowerShell
such as executing a shell command, running multiple commands together, customizing administrative
tasks, performing task automation etc.
cat $SHELL - displays the current shell type you are working on.
which bash
echo $SHELL
ps -p $$
=====================================================================================
==================================================================================
=====================================================================================
==================================================================================
#!/bin/bash
mydata="Hello, world!"
echo $mydata
=====================================================================================
=================================================================================
#!/bin/bash
=====================================================================================
==================================================================================
read username
echo $username
# reads input from the user and puts it in the newusername variable
echo $newusername
echo ""
echo $password
if you don’t wish to specify the variable name for the read we can use $REPLY to echo the value
#!/bin/bash
read
=====================================================================================
==================================================================================
Argument Passing
We can pass arguments that can be used inside the scripts when it is executed.
Those arguments can be accessed by the script using special variables like $1 $2 $3 etc.
=====================================================================================
==================================================================================
Arithmetic Operations
In shell scripting, to perform arithmetic operations we need to use double parenthesis (( )) which is used
for arithmetic expansion on integers.
#!/bin/bash
n1=10
n2=5
Conditions:
#!/bin/bash
my_string=""
else
fi
#!/bin/bash
my_string="Hello, World!"
else
#!/bin/bash
string1="apple"
string2="apple"
else
fi
#!/bin/bash
#!/bin/bash
string1="apple"
string2="orange"
else
fi
#!/bin/bash
num1=5
num2=5
else
fi
#!/bin/bash
num1=5
num2=10
else
fi
#!/bin/bash
num1=5
num2=10
else
fi
#!/bin/bash
num1=5
num2=5
else
fi
#!/bin/bash
num1=10
num2=5
else
fi
#!/bin/bash
num1=5
num2=5
else
fi
#!/bin/bash
!/bin/bash
read username
read password
else
fi
[[ X || Y ]] - Or
!/bin/bash
read username
read password
else
fi
=====================================================================================
==================================================================================
[[ -e FILE ]] - Exists
#!/bin/bash
file_path="/path/to/file.txt"
else
fi
[[ -r FILE ]] - Readable
#!/bin/bash
file_path="/path/to/file.txt"
else
fi
#!/bin/bash
directory_path="/path/to/directory"
else
fi
#!/bin/bash
file_path="/path/to/file.txt"
else
fi
#!/bin/bash
file_path="/path/to/file.txt"
else
fi
[[ -f FILE ]] - File
#!/bin/bash
file_path="/path/to/file.txt"
else
fi
file_path="/path/to/executable"
else
fi
=====================================================================================
==================================================================================
Loops:
if else loop is a conditional statement that allows executing different commands based on the
condition true/false.
#!/bin/bash
if [[ -e ./ifelse.sh ]]
then
else
fi
elif is a combination of both else and if. It is used to create multiple conditional statements
#!/bin/bash
read n
if [ $n -eq 101 ];
then
then
then
else
=====================================================================================
==================================================================================
The for loop is used to iterate over a sequence of values and below is the syntax
#!/bin/bash
for i in {1..10}
do
done
=====================================================================================
===================================================================================
while
The while loop is used to execute a set of commands repeatedly as long as a certain condition is true.
#!/bin/bash
count=0
do
echo $count
count=$(($count+1))
done
=====================================================================================
===================================================================================
The until loop in shell scripting is used to execute a block of code repeatedly until a certain condition
is met.
#!/bin/bash
count=1
do
echo $count
count=$(($count+1))
done
=====================================================================================
===================================================================================
Arrays
An array is a variable that can hold multiple values under a single name
=====================================================================================
===================================================================================
Break Statement
break is a keyword. It is a control statement that is used to exit out of a loop ( for, while, or until)
when a certain condition is met.
It means that the control of the program is transferred outside the loop and resumes with the next set
of lines in the script.
#!/bin/bash
count=1
while true
do
break
fi
done
=====================================================================================
===================================================================================
Continue statement
continue is a keyword that is used inside loops (such as for, while, and until) to skip the current
iteration of the loop and move on to the next iteration.
It means that when the continue keyword is encountered while executing a loop the next set of lines
in that loop will not be executed and moves to the next iteration.
#!/bin/bash
for i in {1..10}
do
if [ $i -eq 5 ]
then
continue
fi
echo $i
done
=====================================================================================
===================================================================================
Functions are a block of code which can be used again and again for doing a specific task thus
providing code reusability.
Normal Function:
#!/bin/bash
sum(){
sum_val=$(($n1+$n2))
n1=$1
n2=$2
sum
To access the return value of the function we need to use $? to access that value
#!/bin/bash
sum(){
sum_val=$(($n1+$n2))
return $sum_val
n1=$1
sum
=====================================================================================
===================================================================================
Variables in Functions
The variable is a placeholder for saving a value which can be later accessed using that name. There are
two types of variables
Global - Variable defined outside a function which can be accessed throughout the script
Local - Variable defined inside a function and can be accessed only within it
#!/bin/bash
x=10
y=20
sum(){
sum=$(($x+$y))
sum
local a=20
local b=10
local sub=$(($a-$b))
sub
=====================================================================================
===================================================================================
else
fi
=====================================================================================
===================================================================================
#!/bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 5 ];
break
fi
((count++))
done
=====================================================================================
==================================================================================
#!/bin/bash
read name
=====================================================================================
==================================================================================
#!/bin/bash
n=10
if [ $n -lt 10 ];
then
else
fi
=====================================================================================
==================================================================================
#!/bin/bash
read n
if [ $n -eq 101 ];
then
then
else
fi
=====================================================================================
==================================================================================
Name_of_dir=$1
start_no=$2
end_no=$3
=====================================================================================
==================================================================================
else
fi
=====================================================================================
==================================================================================
Name_of_dir=$1
start_no=$2
end_no=$3
=====================================================================================
==================================================================================
#!/bin/bash
src=/var/log/httpd/access_log
dest=mybackup
time=$(date +"%Y-%m-%d-%H-%M-%S")
backupfile=$dest/$time.tgz
if [ ${?} -eq 0 ]
then
else
exit 1
fi
if [ ${?} -eq 0 ]: This line checks the exit status of the tar command using the special variable $?. If the
exit status is 0, it means the backup was successful.
${?} is a special variable that represents that most recently executed command.
=====================================================================================
==================================================================================
read username
if [ $? -eq 0 ]; then
else
read -p "Do you want to create the user? (y/n) " create_user
echo
else
exit 0
fi
fi
=====================================================================================
==================================================================================
=====================================================================================
==================================================================================
#!/bin/bash
string1="Linux"
string2="Hint"
echo "$string1$string2"
=====================================================================================
==================================================================================
#!/bin/bash
read newdir
mkdir $newdir
=====================================================================================
==================================================================================
#!/bin/bash
read newfile
touch $newfile
=====================================================================================
==================================================================================
#!/bin/bash
read ndir
then
else
`mkdir $ndir`
fi
=====================================================================================
==================================================================================
#!/bin/bash
read fn
rm -i $fn
=====================================================================================
==================================================================================
#!/bin/bash
check_service() {
return 0
else
return 1
fi
fi
=====================================================================================
==================================
#!/bin/bash
get_disk_usage() {
directory=$1
echo $disk_usage
usage=$(get_disk_usage $HOME)
echo "The disk usage of the home directory is: $usage bytes."
=====================================================================================
==================================
#!/bin/bash
get_disk_usage() {
directory=$1
echo $disk_usage
usage=$(get_disk_usage /home)
=====================================================================================
==================================
#!/bin/bash
check_package() {
local PACKAGE_NAME="$1"
then
else
fi
check_package "vim"
check_package "git"
=====================================================================================
==================================
#!/bin/bash
install_package() {
local PACKAGE_NAME="$1"
install_package "vim"
install_package "git"
=====================================================================================
==================================
#!/bin/bash
check_services() {
else
fi
done
=====================================================================================
=================================
#!/bin/bash
2. CREATE SOME FILES IN SIDE THE FOLDER WITH OLDER TIME STAMP (touch -d "Fri, 21 Aug 2023
11:14:00" tcs infosys infotech)
4. MODIFY THE SCRIPT TO DELETE A FILES : (find myfiles -mtime +60 -exec rm -f {} \;)
=====================================================================================
=========================================
echo " Used Memory: $(free -m | awk '/Mem/ {print $3 " MB"}')"
NOTE:
Awk : this is used to divide the data in the format of rows and column’s which are present in a file.
=====================================================================================
=========================================
echo "EBS Volume Usage: $(df -h | grep -E '^/' | awk '{print $4 " free out of " $2}')"
NOTE:
$4 : used mem
$2 : total mem