Introduction
Shell scripting is one of the core skills for any DevOps engineer. It allows automation of repetitive tasks, system administration, monitoring, deployments, and integration with cloud and CI/CD tools.
This article covers the must-know shell scripting concepts required to crack a DevOps trainee / associate / junior DevOps engineer role.
What is a shell?
A shell is a command-line interface (CLI) that acts as a bridge between the user and the operating system.
Why is it Called a “Shell”?
- The kernel is the core of the operating system
- The shell surrounds the kernel and provides a way for users to interact with it that’s why it’s called a shell — it wraps around the kernel.
How a Shell Works
- You type a command (for example:
ls) - The shell interprets the command
- The shell asks the OS (kernel) to execute it
- The result is displayed back to you
Types of Shells:
Shells are broadly classified into Graphical User Interface (GUI) shells and Command Line Interface (CLI) shells, based on how users interact with the operating system.
Graphical User Interface (GUI) Shell
A GUI shell allows users to interact with the system using windows, icons, menus, buttons, and a mouse, instead of typing commands.
Examples:
→ Linux: GNOME
→ Windows: Windows Explorer (Windows Shell), Windows Desktop Environment
→ Apple (macOS): Finder
→ GUI shells are user-friendly and commonly used on desktops but are rarely used on servers.
Command to know which GUI shell is being used
echo $XDG_CURRENT_DESKTOP
Command Line Interface (CLI) Shell
A CLI shell allows users to interact with the operating system by typing text-based commands through a terminal.
Examples:
→ Linux: bash (Bourne Again Shell), sh (Bourne Shell)
→ Windows: command Prompt, powerShell
→ Apple (macOS): zsh (default shell), terminal
→ CLI shells are powerful, fast, and heavily used by system administrators and DevOps engineers.
Types of Linux shells:
i. sh (Bourne Shell): The original Unix shell that provides basic command execution and scripting features. It is lightweight and mainly used for compatibility and simple scripts.
ii. bash (Bourne Again Shell): An enhanced version of sh with features like command history, auto-completion, and job control. It is the default shell in most Linux distributions.
iii. zsh (Z Shell): An advanced shell with powerful auto-completion, spelling correction, and theming support. It is popular among developers for its productivity features.
iv. ksh (Korn Shell): Combines features of sh and csh with strong scripting capabilities. It is commonly used in enterprise and legacy Unix systems.
v. csh (C Shell): Uses C-language-like syntax and provides built-in job control. It is less popular today due to scripting limitations.
vi. fish (Friendly Interactive Shell): Designed for ease of use with smart suggestions and syntax highlighting. It focuses more on interactivity than scripting compatibility.
Commands to know about Shell:
→ echo $0 -> Shows the name of the shell currently in use.
→ cat /etc/shells -> Lists all the shells available and installed on the Linux system.
→ echo $SHELL -> Displays the default shell path assigned to the current user.
What is Shell Scripting?
→ It is an executable file containing several shell commands that executes sequentially.
→ “.sh” is the extension for shell script files.
Steps to Create and Run a Shell Script File:
Note:
--> File will execute from left to right
--> Top to Bottom
--> Line by Line
What is a Variable?
A variable is a named memory location used to store data that can be accessed and modified during script execution.
Declaring and Assigning a Variable:
syntax: declare_variable=assign_value #example: name="Devops"
Accessing a Variable:
Use $ before the variable name to access its value.
#example: echo $name
Taking Input from the User:
The read command is used to take input from the user and store it in a variable.
#example: read username
Example Script: User Input and Variable Access:
#!/bin/bash
echo "Enter your name:" #Devops
read name
echo "Welcome $name"
o/p -> Welcome Devops
What are Operators?
Operators are symbols used to perform operations on variables and values.
Types of Operators:
- Arithmetic Operators: Used to perform mathematical calculations.
→ (+) Addition
→ (-) Subtraction
→ (*) Multiplication
→ (/) Division
→ (%) Modulus
#!/bin/bash
echo enter the first value
read num1
echo enter the second value
read num2
sum=$((num1+num2)) #Addition
sub=$((num1-num2)) #Subtraction
prod=$((num1*num2)) #Multiplication
div=$((num1/num2)) #Division
mod=$((num1%num2)) #Modulus
echo Add:$sum
echo Sub:$sub
echo Mul:$prod
echo Div:$div
echo Mod:$mod
2. Relational Operators: Used to compare two numeric values.
→ (-eq or ==) Equal
→ (-ne or !=) Not Equal
→ (-gt or >) Greater than
→ (-lt or <) Less than
→ (-ge or >=) Greater than / Equal to
→ (-le or <=) Less than / Equal to
#!/bin/bash
echo enter the first value
read a
echo enter the second value
read b
echo "a==b":$((a==b)) #Equals
echo "a!=b":$((a!=b)) #Not Equals
echo "a>b":$((a>b)) #Greater than
echo "a<b":$((a<b)) #Lesser than
echo "a>=b":$((a>=b)) #Greater than or Equal to
echo "a<=b":$((a<=b)) #Lesser than or Equal to
3. Logical Operators: It will check the condition and compare the value and return true or false.
→ (-a or &&) AND → True if both conditions are true
→ (-o or ||) OR → True if any one condition is true
→ (!) NOT → True if the condition is false
#!/bin/bash
echo enter the first binary value
read a
echo enter the second binary value
read b
echo "a AND b":$((a&&b)) #logical AND
echo "a OR":$((a||b)) #logical OR
echo "NOT a":$((!a)) #logical NOT
echo "NOT b":$((!b)) #logical NOT
What are Conditional Statements?
It is used to execute code blocks on whether conditions evaluate to true or false.
Types:
1. if Statement: Executes a block of code when a condition is true.
#!/bin/bash
if [ $a -gt 10 ]
then
echo "A is greater than 10"
fi
2. if–else Statement: Executes one block if the condition is true and another if it is false.
#!/bin/bash
if [ $a -gt 10 ]
then
echo "A is greater than 10"
else
echo "A is less than or equal to 10"
fi
3. elif Statement: Used to check multiple conditions sequentially.
#!/bin/bash
if [ $a -gt 10 ]
then
echo "A is greater than 10"
elif [ $a -eq 10 ]
then
echo "A is equal to 10"
else
echo "A is less than 10"
fi
4. Nested if Statement: An if statement inside another if statement is called a nested if.
#!/bin/bash
if [ $a -gt 0 ]
then
if [ $a -lt 100 ]
then
echo "A is between 1 and 99"
fi
fi
→ String Operators:
=: Checks if two strings are equal!=: Checks if two strings are not equal-z: Checks if a string is null (empty)-n: Checks if a string is not null
#!/bin/bash
str1="DevOps"
str2="Linux"
# Check if strings are equal
if [ "$str1" = "$str2" ]; then
echo "str1 is equal to str2"
else
echo "str1 is not equal to str2"
fi
→ File Test Operators:
-e: Checks if a file or directory exists-f: Checks if a file exists and is a regular file-d: Checks if a directory exists-r: Checks if a file is readable-w: Checks if a file is writable-x: Checks if a file is executable-s: Checks if a file is not empty (size > 0
#!/bin/bash
echo "Enter the file path:"
read filepath
# Check if file exists
if [ -e "$filepath" ]; then
echo "File exists"
else
echo "File does not exist"
fi
Looping Statements:
Looping statements are used to execute a block of code repeatedly until a certain condition is met.
- for Loop: Executes a block of code for each item in a list or range.
syntax:
for variable in list do commands done
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Iteration $i"
done
--------------------
for((i=1;i<=5;i++))
do
echo "Number $i"
done
2. while Loop: Executes a block of code repeatedly while a condition is true.
Syntax:
while [ condition ] do commands done
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo "Count is $count"
((count++))
done
3. until Loop: Executes a block of code repeatedly until a condition becomes true.
Syntax:
until [ condition ] do commands done
#!/bin/bash
count=1
until [ $count -gt 5 ]
do
echo "Count is $count"
((count++))
done
4. Nested Loops: A loop inside another loop is called a nested loop.
#!/bin/bash
for i in 1 2 3
do
for j in a b c
do
echo "$i - $j"
done
done
Functions:
- It allows you to group commands together into single unit & reuse them throughout your script.
- This can make scripts more organized, readable and maintainable.
Declaring a Function:
Syntax1: function function_name {
commands
}
Syntax2: function_name() {
commands
}
----------------------------------
#!/bin/bash
greet() {
echo "Hello, DevOps!"
}
# call function:
greet
o/p: Hello, DevOps!
Function Variables Scope:
- Variables are declared into local and global variables
- Variables declared in a script by default is called global variables
- Variable declared directly in function block it is also referred as global variable
- Variable declared with local keyword is called local variable
#!/bin/bash
global_var="I am global"
myfunc() {
local local_var="I am local"
echo $global_var
echo $local_var
}
myfunc
echo $global_var
echo $local_var #Will give blank because local_var is not accessible outside
o/p:
I am global
I am local
I am global
# blank (local_var is not accessible here)
Passing Arguments to a Function:
- Arguments passed to a function are accessed by using $1, $2, etc.
- It is just like script arguments.
#!/bin/bash
sum() {
echo "Sum: $(($1 + $2))"
}
sum 10 20
o/p: sum: 30
Returning Values from a Function:
- Shell functions can return values using the “return” command
- It will return number only from range “ 0 to 255 “.
#!/bin/bash
square() {
echo $(($1 * $1))
}
result=$(square 5)
echo "Square is $result"
o/p: Square is 25
Redirections:
Redirection is the process of sending the output of a command to a file or another command instead of the terminal.
Output Redirection:
1. >
What it does: Sends command output to a file and replaces old content.
Example:
echo "Hello" > file.txt #file.txt will contain only Hello
2. >>
What it does: Sends command output to a file and adds it at the end.
Example:
echo "World" >> file.txt #file.txt will now have Hello and World
Error Redirection:
1. 2>
What it does: Saves error messages into a file
Example:
ls wrongfile 2> error.txt #Error message goes into error.txt,not on screen
2. 2>>
What it does: Adds error messages to a file without deleting old errors
Example:
ls anotherwrongfile 2>> error.txt #New error is added to error.txt
Input Redirection:
1. <
What it does: Read input from a file instead of keyboard
Example:
sort < names.txt #Reads names.txt and prints the sorted names
To Redirect both Output and Error :
1. &>
What it does: Saves both output and error into one file
Example:
ls file1 wrongfile &> all.txt #Both success output & error go into all.txt
Note: We are having special file in Linux → /dev/null What it does: Throws away all the output
Example:
ls > /dev/null #ls runs, but you see nothing on the screen.
Subshell:
A Subshell is a child shell that runs a group of commands in isolation from the current shell.
Key Points
- Created using parentheses ()
- Useful for isolating commands
- Changes inside the subshell do not affect the main shell
#!/bin/bash
var="Parent"
echo "Before subshell: $var"
(
var="Child"
echo "Inside subshell: $var"
)
echo "After subshell: $var"
Command Substitution:
Command substitution allows you to use the output of a command as a value for a variable or directly in a command.
Syntax: $(): $(command)
#!/bin/bash
# Using $()
current_date=$(date)
echo "Today is $current_date"
Note:
| Syntax | Purpose |
| ------------------- | ----------------------------------- |
| `if command ; then | To check if a command is successful |
| `()` | Subshell |
| `$()` | Command substitution |
| `$(( ))` | Arithmetic operators |
| `[]` or `[[]]` | Logical operators |
Conclusion:
Shell scripting is an essential skill for DevOps engineers to automate system tasks and improve efficiency. It is widely used for system administration, monitoring, backups, and CI/CD automation.
Learning core concepts like variables, conditions, loops, and functions builds a strong scripting foundation. Mastering shell scripting helps reduce manual effort and prepares candidates for real-world DevOps roles.
You can also check out my previously written Linux article for a comprehensive understanding of Linux concepts.
Comments
Loading comments…