If you're learning DevOps, Linux, or Cloud Computing, Bash scripting is one of the most valuable skills you can develop.
Up until now, you've probably been running Linux commands one by one in the terminal. But in real-world DevOps, repeating the same commands manually isn't efficient. Instead, we automate those tasks using shell scripts.
Whether you're deploying applications, monitoring servers, creating backups, or scheduling maintenance jobs, Bash scripting is often the first step toward automation.
In this article, I'll cover:
✅ Why Bash scripting matters
✅ Terminal text editors (Nano & Vim)
✅ Creating your first Bash script
✅ Variables and special variables
✅ Conditionals (if, else)
✅ Loops (for, while)
✅ Functions
✅ Automating tasks with Cron
Let's get started.
Why Bash Scripting Matters
Imagine typing the same five commands every day to:
- Deploy an application
- Back up a database
- Restart a service
- Clean old log files
Instead of repeating these commands manually, you can place them inside a script and execute them with a single command.
That's automation.
In fact, Bash scripting is the foundation of many DevOps tools. Before Jenkins pipelines, Ansible playbooks, or Terraform modules execute tasks, they're often running shell commands behind the scenes.
Learning Bash means learning how automation actually works.
Terminal Text Editors
When working on remote Linux servers through SSH, you usually won't have a graphical editor like VS Code.
Instead, you'll use terminal-based editors.
The two most common are Nano and Vim.
Nano
Nano is beginner-friendly and easy to use.
Open a file:
nano script.sh
Useful shortcuts:
| Shortcut | Action |
|---|---|
| Ctrl + O | Save |
| Ctrl + X | Exit |
| Ctrl + K | Cut a line |
| Ctrl + U | Paste |
| Ctrl + W | Search |
Nano displays these shortcuts at the bottom of the screen, making it easy for beginners.
Vim
Vim is one of the most powerful text editors available on Linux.
Open a file:
vim script.sh
Unlike Nano, Vim uses different modes.
| Mode | Purpose |
|---|---|
| Normal | Execute commands |
| Insert | Type text |
| Command | Save, quit, search |
Essential Vim commands:
i → Enter Insert mode
Esc → Return to Normal mode
:w → Save
:q → Quit
:wq → Save and Quit
:q! → Quit without saving
dd → Delete current line
/text → Search for text
While Vim has a learning curve, it's installed on almost every Linux system, making it a valuable tool to know.
Creating Your First Bash Script
A Bash script is simply a text file containing Linux commands.
Every script should begin with a shebang.
#!/bin/bash
The shebang tells Linux which interpreter should execute the script.
Example:
#!/bin/bash
echo "Hello DevOps!"
Save the file as:
hello.sh
Make it executable:
chmod +x hello.sh
Run it:
./hello.sh
You can also execute it without making it executable:
bash hello.sh
Working with Variables
Variables store values that can be reused throughout a script.
Example:
#!/bin/bash
name="DevOps Engineer"
count=5
echo "Hello, $name"
echo "Count: $count"
Important Rules
- No spaces around
= - Use
$when accessing a variable - Wrap variables inside double quotes
Correct:
name="John"
echo "$name"
Incorrect:
name = "John"
Command Substitution
Store command output inside a variable.
Example:
current_date=$(date)
echo "$current_date"
Another example:
file_count=$(ls | wc -l)
echo "$file_count files found."
This technique is commonly used in automation scripts.
Special Variables
Bash provides several built-in variables.
| Variable | Purpose |
|---|---|
$0 |
Script name |
$1 |
First argument |
$2 |
Second argument |
$# |
Number of arguments |
$? |
Exit status of previous command |
Example:
./deploy.sh production
Inside the script:
echo "$1"
Output:
production
Using Conditionals
Conditionals allow scripts to make decisions.
Example:
disk_usage=85
if [ "$disk_usage" -gt 80 ]; then
echo "Disk usage is high!"
else
echo "Disk usage is healthy."
fi
Common Comparison Operators
| Operator | Meaning |
|---|---|
-eq |
Equal |
-ne |
Not equal |
-gt |
Greater than |
-lt |
Less than |
-ge |
Greater than or equal |
-le |
Less than or equal |
== |
String equality |
!= |
String inequality |
-f |
File exists |
-d |
Directory exists |
Checking Whether a File Exists
if [ -f "app.log" ]; then
echo "Log file found."
else
echo "Log file missing."
fi
This is a common pattern in deployment and monitoring scripts.
Using Loops
Loops execute commands repeatedly.
For Loop
for server in web1 web2 web3
do
echo "Deploying to $server"
done
Loop through files:
for file in *.log
do
echo "$file"
done
Loop over numbers:
for i in {1..5}
do
echo "$i"
done
While Loop
count=1
while [ "$count" -le 5 ]
do
echo "$count"
count=$((count+1))
done
Real Example: Retry Until Success
attempt=0
while [ "$attempt" -lt 5 ]
do
if curl -sf http://localhost:8080/health
then
echo "Service is running."
break
fi
echo "Retrying..."
attempt=$((attempt+1))
sleep 5
done
This pattern is widely used in deployment scripts.
Creating Functions
Functions help organize larger scripts.
Example:
log_message() {
local message=$1
echo "$(date): $message"
}
Call the function:
log_message "Deployment started"
log_message "Deployment completed"
Using functions makes scripts easier to read and maintain.
Automating Tasks with Cron
Automation becomes even more powerful when scripts run automatically.
Linux provides cron for scheduling tasks.
Edit your cron jobs:
crontab -e
Cron format:
* * * * * command
│ │ │ │ │
│ │ │ │ └── Day of Week
│ │ │ └──── Month
│ │ └────── Day of Month
│ └──────── Hour
└────────── Minute
Common Cron Examples
Run every day at 2:30 AM:
30 2 * * * /home/user/backup.sh
Run every hour:
0 * * * * /home/user/health-check.sh
Run every Monday at 9 AM:
0 9 * * 1 /home/user/report.sh
Run every five minutes:
*/5 * * * * /home/user/monitor.sh
Logging Cron Output
Always redirect cron output to a log file.
30 2 * * * /home/user/backup.sh >> /home/user/backup.log 2>&1
This captures both:
- Standard output
- Error messages
Making troubleshooting much easier.
Best Practices for Bash Scripts
- Start every script with
#!/bin/bash - Use meaningful variable names
- Always quote variables
- Use functions for reusable logic
- Test scripts before running them in production
- Use absolute paths in cron jobs
- Log script output for easier debugging
- Add comments to improve readability
Quick Command Reference
| Command | Purpose |
|---|---|
nano file.sh |
Open file in Nano |
vim file.sh |
Open file in Vim |
chmod +x file.sh |
Make script executable |
./file.sh |
Run script |
bash file.sh |
Execute with Bash |
crontab -e |
Edit cron jobs |
date |
Current date and time |
$(command) |
Command substitution |
$? |
Previous command exit status |
$# |
Number of arguments |
Final Thoughts
Bash scripting is where Linux commands become automation.
By learning how to write scripts, use variables, create loops, organize code with functions, and schedule jobs with Cron, you're building the foundation for more advanced DevOps tools like Jenkins, Ansible, Terraform, and Kubernetes.
These concepts may seem simple now, but they're used every day in real production environments.
If you have any Bash scripting tips or favorite automation tricks, feel free to share them in the comments.
Happy Learning! 🐧🚀
Top comments (0)