Introduction to Bash Scripting: A Beginner-Friendly Guide for DevOps Engineers
Table of contents
- Introduction
- Introduction to Bash
- What is Bash Scripting?
- Installing a Terminal
- Getting Started with Bash Scripting
- Basic Bash Scripts to Practice:
- Example-1
- Example-2
- Example-3
- Beginner-Friendly Bash Scripts for DevOps Engineers
- 1. Disk Usage Alert Script
- Create a Bash Script
- Add the Shebang
- Make the Script Executable and Run the Script
- 2. User Account Checker Script
- Create a Bash Script
- Add the Shebang
- Make the Script Executable and Run the Script
- 3. Service Status Checker Script
- Create a Bash Script
- Add the Shebang
- Make the Script Executable and Run the Script
- 4. Log Rotation Script
- Create a Bash Script
- Add the Shebang
- Make the Script Executable and Run the Script
- 5. CPU Usage Monitoring Script
- Create a Bash Script
- Add the Shebang
- Make the Script Executable and Run the Script
- Conclusion
Welcome, homies! As promised, we’re here to conquer the final boss of Linux—Bash Scripting. This is the game-changer for DevOps engineers, the ultimate tool for automating tasks and making your life a whole lot easier. Trust me, this topic is a big deal, and it’s going to take your skills to the next level.
Now, fair warning: this blog is going to be longer than usual. Why? Because we’re diving deep—from beginner-friendly basics to advanced-level scripting that’s super handy for all your DevOps day-to-day hustles. So grab your favorite snack, find a comfy chair, and get ready to embark on an epic journey into the Bash Scripting universe. Let’s make magic happen!
Introduction
Shell scripting is a critical skill for automating routine tasks on Linux systems, reducing manual effort, and enhancing productivity. By leveraging foundational Linux commands like touch
, ls
, and vim
, users can create, manage, and edit shell scripts with ease. The shebang (#!
) line plays a key role by specifying the interpreter (e.g., Bash, Ksh, or Sh) to execute the script, with Bash being the most popular. This guide delves into writing and executing shell scripts, showcasing their importance in Linux environments.
Key Insights
Automation as a Time-Saver:
Shell scripting automates repetitive tasks, like file creation and data processing, allowing users to focus on complex challenges and increasing overall efficiency.
Master the Basics First:
Before diving into scripts, understanding core commands (touch
, ls
, vi
) is essential. These are the building blocks of effective shell scripting and ensure a smoother learning experience.
The Shebang Line:
The first line of any script, #!/bin/bash
(or other shells), determines the interpreter, ensuring scripts execute correctly across systems. Compatibility depends on choosing the right shell for the job.
Manual Pages (man):
The man
command is an indispensable resource, offering command syntax, options, and examples. Beginners and experts alike rely on it for troubleshooting and refining scripts.
Why Bash Rules:
Bash is widely used for its flexibility and ease of learning. Its support for loops, conditionals, and other programming constructs makes it suitable for simple automation or advanced workflows.
Remote Scripting Made Easy:
SSH tools like PuTTY and iTerm enable seamless access to Linux servers for remote script execution—a vital capability for system admins managing multiple servers.
Text Editors Matter:
Proficiency in vi
or vim
is crucial for creating well-structured scripts. These editors offer features like syntax highlighting and navigation shortcuts that improve script management.
Introduction to Bash
In DevOps, automation is the cornerstone of efficiency, and Bash scripting is one of the most powerful tools for achieving this. It simplifies repetitive tasks, streamlines processes, and enhances productivity. In this guide, we’ll cover the basics of Bash scripting and provide simple, practical examples tailored for those learning Bash scripting in a Linux environment.
What is Bash Scripting?
Bash scripting involves writing a series of commands in a file, which can be executed sequentially in a Linux terminal. As DevOps engineers, this skill helps automate system monitoring, file management, and other administrative tasks.
Why Use Bash Scripting?
Automation: Simplifies repetitive tasks like log management and backups.
Efficiency: Executes complex tasks in seconds.
Simplicity: Works seamlessly with Linux commands.
Powerful Integration: Combines commands with variables, loops, and conditionals.
Installing a Terminal
Guess what? You don’t have to install a new terminal for this guide—you can stick with the trusty Linux terminal you already have. But hey, I’ve got a favorite! Meet Warp Terminal, my go-to for a modern, snappy terminal experience that makes scripting feel futuristic.
If you’re curious and want to give Warp Terminal a spin, here’s how you can download and install it to write your Bash scripts like a pro.
Quick Note: Everything we cover here works just as smoothly on the traditional Linux terminal as it does on Warp Terminal. So, no worries if you’d rather stick to the classics!
Visit the official website of Warp https://www.warp.dev/.
Download the package as per your system. I am on Ubuntu so I will download the .deb in my system.
Once you’re done run the command
sudo dpkg -i
to install the Warp Terminal.Once you’re done installing, It will ask you for the Sign-up.
Congratulations! We have successfully installed Warp Terminal.
Getting Started with Bash Scripting
1. Create a Bash Script
Use a text editor to create a script file and save it with a .sh
extension:
vim 01_welcome.sh
2. Add the Shebang
Add the shebang (#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
echo "Welcome to Bash Scripting Folks!"
3. Make the Script Executable
Set executable permission for the script:
chmod +x 01_welcome.sh
4. Run the Script
Execute the script by providing its path:
./01_welcome.sh
Basic Bash Scripts to Practice:
Example-1
1. Create a Bash Script
Use a text editor to create a script file and save it with a .sh
extension:
vim 02_userinput.sh
2. Add the Shebang
Add the shebang (#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
echo "Enter your age: "
read age
eacho "Your age is $age"
3. Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 02_usernput.sh
./02_userinput.sh
Example-2
1. Create a Bash Script
Use a text editor to create a script file and save it with a .sh
extension:
vim 03_condition.sh
2. Add the Shebang
Add the shebang (#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
read -p "Enter your marks: " marks
if [[ $marks -ge 80 ]]
then
echo "Distinction"
elif [[ $marks -ge 65 ]]
then
echo "First Class"
elif [[ $marks -ge 35 ]]
then
echo "Second Class"
else
echo "Fail"
fi
3. Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 03_condition.sh
./03_condition.sh
Example-3
1. Create a Bash Script
Use a text editor to create a script file and save it with a .sh
extension:
vim 04_directories.sh
2. Add the Shebang
Add the shebang (#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 22-01-2025
# Creating directories using loop
#######################################
echo "Enter the Directory name: "
read name
echo "Enter the starting number: "
read start_num
echo "Enter the ending number: "
read end_num
# for i in {$start..$end}
for (( i = start_num; i <= end_num; i++ ));
do
mkdir $name$i
done
echo "Directories are created"
3. Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 4_directories.sh
./04_directories.sh
Beginner-Friendly Bash Scripts for DevOps Engineers
1. Disk Usage Alert Script
This script monitors disk usage and sends an alert if usage exceeds a threshold.
Create a Bash Script
Use a text editor to create a script file and save it with a
.sh
extension:vim 05_disk_alert.sh
Add the Shebang
Add the shebang (
#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 23-01-2025
# Disk Usage Alert Script
#######################################
THRESHOLD=80
echo "Checking disk usage..."
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "Warning: Disk usage is at ${USAGE}%!"
else
echo "Disk usage is within safe limits (${USAGE}%)."
fi
Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 05_disk_alert.sh ./05_disk_alert.sh
Use Case: Run this script periodically to ensure your system has sufficient disk space.
2. User Account Checker Script
This script checks if a specific user exists on the system.
Create a Bash Script
Use a text editor to create a script file and save it with a
.sh
extension:vim 06_user_check.sh
Add the Shebang
Add the shebang (
#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 23-01-2025
# User Account Checker Script
#######################################
USER="jordan"
if id "$USER" &>/dev/null; then
echo "User $USER exists on the system."
else
echo "User $USER does not exist."
fi
Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 06_user_check.sh ./06_user_check.sh
Use Case: Use this script to verify user accounts before running tasks that require specific user privileges.
3. Service Status Checker Script
This script checks if a given service (e.g., SSH) is running and restarts it if it's not.
Create a Bash Script
Use a text editor to create a script file and save it with a
.sh
extension:vim 07_service_status.sh
Add the Shebang
Add the shebang (
#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 23-01-2025
# Service Status Checker Script
#######################################
SERVICE="ssh"
if systemctl is-active --quiet "$SERVICE"; then
echo "Service $SERVICE is running."
else
echo "Service $SERVICE is not running. Restarting..."
sudo systemctl start "$SERVICE"
echo "Service $SERVICE has been restarted."
fi
Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 07_service_status.sh ./07_service_status.sh
Use Case: Ensure critical services are always running on your Linux server.
4. Log Rotation Script
This script compresses and archives log files to save space and organize them.
Create a Bash Script
Use a text editor to create a script file and save it with a
.sh
extension:vim 08_logs.sh
Add the Shebang
Add the shebang (
#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 23-01-2025
# Log Rotation Script
#######################################
LOG_DIR="/var/log/myapp"
ARCHIVE_DIR="/var/log/myapp/archive"
DATE=$(date +%Y-%m-%d)
echo "Rotating logs..."
mkdir -p "$ARCHIVE_DIR"
tar -czf "$ARCHIVE_DIR/logs-$DATE.tar.gz" "$LOG_DIR"/*.log
rm "$LOG_DIR"/*.log
echo "Logs have been rotated and archived."
Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 09_logs.sh ./08_logs.sh
Use Case: Prevent logs from consuming excessive disk space while keeping backups.
5. CPU Usage Monitoring Script
This script monitors CPU usage and alerts if it exceeds a defined threshold.
Create a Bash Script
Use a text editor to create a script file and save it with a
.sh
extension:vim 09_cpu_usage.sh
Add the Shebang
Add the shebang (
#!/bin/bash
) at the top of the file to specify the script interpreter:
#!/bin/bash
######################################
# Author- Rajratan Gaikwad
# Date- 23-01-2025
# CPU Usage Monitoring Script
#######################################
THRESHOLD=75
echo "Checking CPU usage..."
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | cut -d'.' -f1)
if [ "$CPU" -gt "$THRESHOLD" ]; then
echo "Warning: CPU usage is at ${CPU}%!"
else
echo "CPU usage is normal (${CPU}%)."
fi
Make the Script Executable and Run the Script
Execute the script by providing its path:
chmod +x 09_cpu_usage.sh ./09_cpu_usage.sh
Use Case: Keep track of CPU usage to avoid server overload.
Conclusion
Bash scripting is an essential skill for DevOps engineers working with Linux. The examples above demonstrate how to automate common tasks like monitoring disk and CPU usage, checking user accounts, managing services, and organizing logs. These scripts are simple yet practical, laying the groundwork for more advanced automation in the future.
Experiment with these scripts, tweak them to suit your needs and let the power of Bash scripting elevate your DevOps workflow.
Uff, what an incredible journey it’s been! Yes, my friends, we’ve officially mastered Linux for DevOps. This marks the epic conclusion of our Linux series, in which we explored everything from understanding Linux to installing it, Mastering Basic Commands with hands-on fun, Navigating the Linux Filesystem, Unlocking File Permissions, Diving into Text Editors, and finally, Conquering Bash Scripting.
What a thrilling ride, right? By covering all of this, we’ve built a rock-solid foundation in Linux—one we can proudly say is essential for any DevOps engineer. I hope you had as much fun learning as I had sharing this adventure with you!
But wait—don’t go anywhere just yet. Now that you’re comfortable crafting scripts like a pro, it’s time to take things up a notch. Next stop? The programming world—a must-have skill for every DevOps engineer in this fast-paced tech era. So until then, keep practicing, perfect those scripts, and get ready to dive into the exciting realm of coding. Catch you soon, and as always—
Until next time, keep coding, automating, and advancing in DevOps! 😁
Peace out ✌️