Live ChatLogin
PakiWebHost
10 Practical Bash Script Examples Every Linux Server Admin Should Know
Technical Guides

10 Practical Bash Script Examples Every Linux Server Admin Should Know

July 5, 2026 · 5 min read

From automated backups to watchdog services and deployment scripts — ten ready-to-use bash examples that make routine server tasks faster, safer and more consistent.

If you administer a Linux server — even part-time as part of managing your own VPS — the single most useful skill you can develop is writing basic bash scripts. A script turns a five-minute manual routine into a two-second command. Run from cron, it becomes work you never have to remember to do.

This article covers ten practical bash scripts that solve real tasks: backups, monitoring, cleanup, health checks and deployments. Each example is short enough to understand immediately, and each can be adapted to your own server environment.

What makes a good bash script

Before the examples, a few conventions every safe script follows:

#!/bin/bash
set -euo pipefail
  • #!/bin/bash tells the system which interpreter to use
  • set -e stops the script if any command fails
  • set -u treats unset variables as an error
  • set -o pipefail catches failures inside piped commands

These three options prevent a failed step from silently continuing — the single most common source of script-based disasters.

1. Automated website backup

Back up a web root and its database into a date-stamped archive, keeping only the last 14 backups:

#!/bin/bash
set -euo pipefail
BACKUP_DIR="/var/backups"
DB_NAME="mydb"
DB_USER="dbuser"
SITE_DIR="/var/www/mysite"
DATE=$(date +%Y%m%d-%H%M)
mysqldump -u "$DB_USER" "$DB_NAME" > "$BACKUP_DIR/db-$DATE.sql"
tar -czf "$BACKUP_DIR/files-$DATE.tar.gz" "$SITE_DIR"
find "$BACKUP_DIR" -type f -mtime +14 -delete
echo "Backup $DATE complete"

Schedule it daily with cron: 0 3 * * * /usr/local/bin/backup.sh

10 Practical Bash Script Examples Every Linux Server Admin Should Know

2. Disk usage alert

Check disk usage and send a warning if any partition exceeds 80%:

#!/bin/bash
set -euo pipefail
THRESHOLD=80
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' |
while read -r output; do
  usage=$(echo "$output" | awk '{ print $1 }' | sed 's/%//')
  partition=$(echo "$output" | awk '{ print $2 }')
  if [ "$usage" -ge "$THRESHOLD" ]; then
    echo "WARNING: $partition at ${usage}% capacity"
  fi
done

Pipe the warning to mail, a Slack webhook, or a monitoring service.

3. Service health watchdog

Restart a service if it stops responding. Useful for critical processes:

#!/bin/bash
set -euo pipefail
SERVICE="nginx"
if ! systemctl is-active --quiet "$SERVICE"; then
  systemctl restart "$SERVICE"
  echo "$SERVICE was down and has been restarted" | logger
fi

Run every minute from cron to keep core services alive without human intervention.

4. Remove old log files

Keep the last 7 days' worth of application logs and purge the rest:

#!/bin/bash
set -euo pipefail
LOG_DIR="/var/log/myapp"
find "$LOG_DIR" -name "*.log" -type f -mtime +7 -delete
echo "Cleaned logs older than 7 days in $LOG_DIR"

Adjust the +7 to match your retention policy.

5. Website health check

Check if a site returns HTTP 200; log failures for review:

#!/bin/bash
set -euo pipefail
URL="https://example.com"
HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}" "$URL")
if [ "$HTTP_CODE" -ne 200 ]; then
  echo "$URL returned HTTP $HTTP_CODE at $(date)" >> /var/log/healthcheck.log
fi

Extend it to hit multiple sites: loop over a list of URLs in a config file.

10 Practical Bash Script Examples Every Linux Server Admin Should Know

6. Database dump with rotation

Dump all databases on a server and keep the newest 30 files:

#!/bin/bash
set -euo pipefail
OUTPUT="/var/db-backups"
mkdir -p "$OUTPUT"
mysqldump --all-databases | gzip > "$OUTPUT/alldb-$(date +%F-%H%M).sql.gz"
find "$OUTPUT" -name "*.sql.gz" -type f -mtime +30 -delete

For PostgreSQL, substitute pg_dumpall.

7. Monitor failed SSH logins

Check recent failed authentication attempts and flag a high threshold:

#!/bin/bash
set -euo pipefail
THRESHOLD=10
FAILED=$(journalctl -u sshd --since "24 hours ago" | grep "Failed password" | wc -l)
if [ "$FAILED" -ge "$THRESHOLD" ]; then
  echo "ALERT: $FAILED failed SSH logins in the last 24 hours"
fi

Combine with a ban script or a notification to check your auth log.

8. Scheduled log rotation

Archive and compress yesterday's access log instead of waiting for logrotate:

#!/bin/bash
set -euo pipefail
LOG="/var/log/nginx/access.log"
ARCHIVE="/var/log/nginx/archive/access-$(date -d yesterday +%F).log.gz"
mv "$LOG" "/tmp/access-rotate"
kill -USR1 $(cat /var/run/nginx.pid)
gzip -c "/tmp/access-rotate" > "$ARCHIVE"
rm "/tmp/access-rotate"

Sending the USR1 signal tells nginx to reopen its log file without dropping connections.

9. Resource snapshot

Log CPU, memory and disk load to a file at intervals — useful for diagnosing intermittent problems:

#!/bin/bash
set -euo pipefail
LOGFILE="/var/log/resource-snapshot.log"
{
  echo "=== $(date) ==="
  echo "LOAD: $(uptime | awk -F'load average:' '{print $2}')"
  echo "MEM: $(free -m | awk '/^Mem:/ {print $3"MB used / "$2"MB total"}')"
  echo "DISK: $(df -h / | awk 'NR==2 {print $5}')"
} >> "$LOGFILE"

10. Simple deployment script

Pull the latest code, install dependencies and restart the application:

#!/bin/bash
set -euo pipefail
DEPLOY_DIR="/var/www/myapp"
cd "$DEPLOY_DIR"
git pull origin main
npm install
npm run build
pm2 restart myapp
echo "Deployed revision $(git rev-parse --short HEAD) at $(date)"

Adapt the build step for your stack — Rails, Laravel, Python — and guard the script with SSH key access only.

Running scripts with cron

To run any script automatically, make it executable (chmod +x script.sh) and add a cron job with crontab -e:

# Every day at 3am
0 3 * * * /usr/local/bin/backup.sh
# Every 5 minutes
*/5 * * * * /usr/local/bin/healthcheck.sh

Always test a new script by hand once before trusting it to cron. A typo that looks harmless in interactive mode can become destructive when repeated automatically.

The bottom line

Bash scripting is the simplest force multiplier available to any server admin. The ten examples here — backups, monitoring health, log rotation, alerts, deployment — cover the tasks that most people either forget to do manually or waste hours repeating. Each can be written, tested and deployed in minutes on your PakiWebHost VPS, and together they turn a hands-on server into something that mostly runs itself.

Ready to launch faster, more reliable hosting?

Get NVMe-powered hosting with free migrations, free SSL and 24/7 support — plans from $1.99/mo.

Frequently Asked Questions

No. Each script is short enough to read and understand in a few minutes. If you can use the terminal and make a file executable (chmod +x), you can use every example here. Always test them manually before putting them in cron.

Yes. The scripts use standard Linux tools — bash, mysqldump, curl, grep, awk, systemctl — that are installed on virtually every major distribution including Ubuntu, Debian, AlmaLinux and CentOS.

On managed shared hosting you generally cannot run custom scripts or install cron jobs that control system services. These examples are designed for unmanaged or semi-managed VPS hosting where you have root access and full control over cron and system utilities.

Make the script executable (chmod +x script.sh), run crontab -e, and add a line specifying the schedule and full path to the script. For example, 0 3 * * * /path/to/script.sh runs it at 3:00 a.m. daily. Test the script manually first before trusting cron.

Related Articles