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
Enter fullscreen mode Exit fullscreen mode
Useful shortcuts:
Shortcut Action Ctrl + O Save Ctrl + X Exit Ctrl + K Cut a line Ctrl + U Paste Ctrl + W SearchNano 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
Enter fullscreen mode Exit fullscreen mode
Unlike Nano, Vim uses different modes.
Mode Purpose Normal Execute commands Insert Type text Command Save, quit, searchEssential 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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
The shebang tells Linux which interpreter should execute the script.
Example:
#!/bin/bash
echo "Hello DevOps!"
Enter fullscreen mode Exit fullscreen mode
Save the file as:
hello.sh
Enter fullscreen mode Exit fullscreen mode
Make it executable:
chmod +x hello.sh
Enter fullscreen mode Exit fullscreen mode
Run it:
./hello.sh
Enter fullscreen mode Exit fullscreen mode
You can also execute it without making it executable:
bash hello.sh
Enter fullscreen mode Exit fullscreen mode
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"
Enter fullscreen mode Exit fullscreen mode
Important Rules
- No spaces around
= - Use
$when accessing a variable - Wrap variables inside double quotes
Correct:
name="John"
echo "$name"
Enter fullscreen mode Exit fullscreen mode
Incorrect:
name = "John"
Enter fullscreen mode Exit fullscreen mode
Command Substitution
Store command output inside a variable.
Example:
current_date=$(date)
echo "$current_date"
Enter fullscreen mode Exit fullscreen mode
Another example:
file_count=$(ls | wc -l)
echo "$file_count files found."
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
Inside the script:
echo "$1"
Enter fullscreen mode Exit fullscreen mode
Output:
production
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
Loop through files:
for file in *.log
do
echo "$file"
done
Enter fullscreen mode Exit fullscreen mode
Loop over numbers:
for i in {1..5}
do
echo "$i"
done
Enter fullscreen mode Exit fullscreen mode
While Loop
count=1
while [ "$count" -le 5 ]
do
echo "$count"
count=$((count+1))
done
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
This pattern is widely used in deployment scripts.
Creating Functions
Functions help organize larger scripts.
Example:
log_message() {
local message=$1
echo "$(date): $message"
}
Enter fullscreen mode Exit fullscreen mode
Call the function:
log_message "Deployment started"
log_message "Deployment completed"
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
Cron format:
* * * * * command
β β β β β
β β β β βββ Day of Week
β β β βββββ Month
β β βββββββ Day of Month
β βββββββββ Hour
βββββββββββ Minute
Enter fullscreen mode Exit fullscreen mode
Common Cron Examples
Run every day at 2:30 AM:
30 2 * * * /home/user/backup.sh
Enter fullscreen mode Exit fullscreen mode
Run every hour:
0 * * * * /home/user/health-check.sh
Enter fullscreen mode Exit fullscreen mode
Run every Monday at 9 AM:
0 9 * * 1 /home/user/report.sh
Enter fullscreen mode Exit fullscreen mode
Run every five minutes:
*/5 * * * * /home/user/monitor.sh
Enter fullscreen mode Exit fullscreen mode
Logging Cron Output
Always redirect cron output to a log file.
30 2 * * * /home/user/backup.sh >> /home/user/backup.log 2>&1
Enter fullscreen mode Exit fullscreen mode
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 Purposenano 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! π§π
λ΅κΈ λ¨κΈ°κΈ°