Bash scripting ??
Getting Started
- File Extension: Bash scripts are typically saved with a
.shextension. - The Shebang: Every script must begin with a shebang (
#!/bin/bashor#!/usr/bin/env bash) on the very first line. This tells the operating system's program loader to interpret and execute the file using Bash.
Core Concepts
Comments
Use # to write non-executing code. Developers use comments to document logic or write instructions.
# This is a comment. The system will ignore this line.Variables
Variables store data for later use, such as strings, numbers, or characters. Note: Do not put spaces around the = sign.
country="Mexico"
age=25Control Flow & Loops
If-Else Conditions
Used to execute code blocks based on specific conditions.
if [[ condition ]]; then
# Code to run if condition is true
elif [[ condition ]]; then
# Code to run if first condition is false, but this one is true
else
# Code to run by default if no conditions match
fiWhile Loops
Repeats a block of code as long as the specified condition remains true.
while [[ condition ]]; do
# Code statement
doneFor Loops
Get Mercy Obasi’s stories in your inbox
Join Medium for free to get updates from this writer.
Iterates over a fixed sequence or range of items.
for i in {1..5}; do
echo "Iteration $i"
doneCase Statements
An efficient alternative to deeply nested if-else blocks when matching a single variable against multiple patterns.
case $expression in
pattern1)
# Block of code
;;
pattern2)
# Block of code
;;
*)
# Default case (matches anything else)
;;
esacCron Expressions & Automation
Cron is a time-based job scheduler in Unix-like operating systems.
* * * * * /path/to/command_or_script.sh
│ │ │ │ │
│ │ │ │ └─ Day of the week (0 - 6) (0 is Sunday)
│ │ │ └─ Month of the year (1 - 12)
│ │ └─ Day of the month (1 - 31)
│ └─ Hour of the day (0 - 23)
└─ Minute of the hour (0 - 59)Example Schedules
0 0 * * * /home/user/backup.sh➔ Runs every single day at exactly midnight.30 8 * * 1 /home/user/report.sh➔ Runs every Monday at 8:30 AM.*/15 * * * * /home/user/check.sh➔ Runs every 15 minutes (note the standard*/15syntax).0 12 1 * * /home/user/rent.sh➔ Runs at 12:00 PM on the 1st day of every month.15 * * * *➔ Runs at exactly minute 15 of every hour (e.g., 12:15, 1:15, 2:15).
Cron Best Practices
- Keep Logic in a Script: Cron executes tasks silently in the background without a visible terminal. Instead of jamming complex, multi-line commands inside your
crontab -efile, write the logic in a.shfile and point Cron to that single file. - Redirect Output to Log Files: Because Cron runs silently, you should redirect the output to a
.logfile to track success and troubleshoot failures:
0 0 * * * /home/user/run_all.sh >> /home/user/script_output.log 2>&1Understanding 2>&1:
>> appends standard output (successful logs) to your file.
2>&1 ensures that standard error (critical failure messages) is redirected into the same log file, allowing you to debug issues later.





