A useful Bash script example should solve a real server problem without hiding the risk. For Linux VPS admins, that usually means repeatable checks, clear variables, safe defaults, useful output, and enough logging that another person can understand what happened later.
The examples below are intentionally small. Treat them as starting points, not copy-paste production automation. Change paths, test on a disposable directory, run with a non-critical account first, and add monitoring or alerting only after the script behaves predictably.
Key takeaways
- Put editable variables near the top of each script.
- Use quotes around variables that contain paths or user input.
- Prefer a dry-run or print-only mode before deleting files.
- Log what the script checked and what it changed.
- Test syntax with
bash -n script.shbefore scheduling anything. - For related command-line skills, read the Virtarix guides to Linux command line tips, finding files, VPS backups, and VPS security.
1. A safe Bash script template
Start with a predictable header and variables.
#!/usr/bin/env bash
set -euo pipefail
APP_DIR="./app"
LOG_FILE="./script.log"
echo "[$(date -Is)] starting check for $APP_DIR" | tee -a "$LOG_FILE"
set -euo pipefail helps catch failed commands, unset variables, and broken pipelines. It is useful, but it also makes errors stop the script quickly, so test each script before scheduling it.
2. Disk usage warning script
Use this pattern to warn when a filesystem crosses a threshold.
#!/usr/bin/env bash
set -euo pipefail
MOUNT_POINT="/"
LIMIT=85
USAGE=$(df -P "$MOUNT_POINT" | awk 'NR==2 {gsub("%", "", ); print }')
if (( USAGE >= LIMIT )); then
echo "Disk usage is ${USAGE}% on $MOUNT_POINT"
else
echo "Disk usage is OK: ${USAGE}%"
fi
This is a reporting script, not a cleanup script. Let it alert first. Add automatic cleanup only after you know which files are safe to remove.
3. Search logs for errors
This script searches a log directory and does not fail just because no match exists.
#!/usr/bin/env bash
set -euo pipefail
LOG_DIR="./logs"
PATTERN="error"
grep -R "$PATTERN" "$LOG_DIR" || true
The || true is deliberate. A no-match result from grep should not always be treated as a broken script. If this feeds monitoring, convert the result into the status your monitoring system expects.
4. Create a timestamped backup archive
Use a timestamped filename so one run does not overwrite the last one.
#!/usr/bin/env bash
set -euo pipefail
SOURCE_DIR="./app"
BACKUP_DIR="./backups"
STAMP=$(date +%F-%H%M)
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/app-$STAMP.tar.gz" "$SOURCE_DIR"
echo "Created $BACKUP_DIR/app-$STAMP.tar.gz"
For real VPS backups, copy the archive off-server and test a restore. A local archive is helpful, but it is not a full recovery plan by itself.
5. Preview old files before cleanup
Do not delete first. Print candidates first.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="./logs"
DAYS=14
find "$TARGET_DIR" -type f -name "*.log" -mtime +"$DAYS" -print
After you confirm the output, you can design a controlled cleanup step. Keep the preview mode in the script so future admins can audit what would be removed.
6. Find large files in an application directory
Large files often explain sudden disk pressure.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="./app"
find "$TARGET_DIR" -type f -size +100M -print
Run this before blaming databases or logs. Large uploads, exports, cache files, and failed backups can all hide in application folders.
7. Check whether a web endpoint responds
This pattern captures only the HTTP status code.
#!/usr/bin/env bash
set -euo pipefail
URL="https://example.com/health"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
echo "HTTP status: $STATUS"
Do not turn one failed check into an immediate restart. Retry, log the time, and compare with application logs before automating recovery.
8. Create a simple server report
A daily report can collect useful context before an incident.
#!/usr/bin/env bash
set -euo pipefail
REPORT="./server-report.txt"
{
date -Is
uptime
df -h
free -h
} > "$REPORT"
echo "Wrote $REPORT"
This is intentionally basic. Add application-specific checks after the report proves useful.
9. Check directory size
Use du to summarize a directory before archiving or deleting anything.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="./app"
du -sh "$TARGET_DIR"
Directory size checks are useful before backups, migrations, support handovers, and cleanup windows.
10. Require confirmation for risky actions
Add a confirmation guard before any script that changes files.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="./cache"
read -r -p "Clean cache preview for $TARGET_DIR? Type yes: " ANSWER
if [[ "$ANSWER" != "yes" ]]; then
echo "Cancelled"
exit 0
fi
find "$TARGET_DIR" -type f -name "*.tmp" -print
This example still prints instead of deleting. That is the point: build the safety rails first, then add the destructive action only when the preview is proven.
How to adapt these examples
Use the examples as patterns rather than finished production tools. A reporting script can usually be copied with only path changes, but a script that touches backups, archives, cache, or cleanup needs a written rollback plan. If the script will run unattended, send output to a log file, make failures visible, and avoid prompts that cron cannot answer.
For team environments, keep scripts in version control and include a short comment explaining the owner, purpose, inputs, and expected output. That small habit prevents mystery automation later. A Bash script is easiest to maintain when the next administrator can read the top of the file and immediately know why it exists.
Safety checklist before scheduling a script
Before you add a Bash script to cron or system automation, confirm:
-
bash -npasses. - Variables point at test paths first.
- The script logs useful output.
- Failures stop safely.
- Credentials are not hard-coded.
- Cleanup scripts have a preview mode.
- Backups are restored in a test location.
- Someone else can understand the script from comments and logs.
A small script can do a lot of damage when it runs unattended. Treat automation as production code.
If you want a disposable environment for practicing each Bash script example, Virtarix Cloud VPS plans give you an isolated server for testing backups, log scans, reports, and cleanup previews before they touch production paths.
FAQ
What is a good first Bash script example?
Start with a reporting script that prints disk usage, memory, or log matches. Avoid destructive cleanup until you understand quoting, variables, and exit status.
Should Bash scripts use set -euo pipefail?
It is a useful safety pattern, but it changes failure behavior. Test scripts carefully so expected no-match or optional commands do not stop the whole workflow unexpectedly.
How do I test a Bash script safely?
Run bash -n script.sh for syntax, use test directories, print actions before changing files, and review logs after each run.
Can I run these scripts from cron?
Yes, after testing paths, permissions, environment variables, and logging. Cron has a smaller environment than an interactive shell, so avoid assumptions.
Summary
The best Bash script example for server work is practical, small, and safe. Start with checks and reports, then add automation only when the output is predictable. Use variables, quotes, logs, dry runs, and restore tests wherever the script touches important data.
For VPS administration, Bash is powerful because it turns repeated operational habits into consistent workflows. The discipline is making those workflows readable, testable, and reversible.
Byline: Peter French — Updated 2026-05-18.