Bash is the glue that holds many production systems together. It schedules jobs, parses logs, backs up data, and orchestrates complex workflows. But when a Bash script fails in production, the impact can be immediate and severe. This article provides a practical operations checklist for Bash-based production systems. You will learn how to inventory your environment, configure safely, verify behavior, recover from failures, and establish repeatable operating procedures. Each section includes concrete commands, configuration snippets, and expected results you can adapt to your own environment.
Version and Environment Inventory
Before making any changes or performing maintenance, you need a clear picture of your Bash environment. This includes the Bash version, operating system, kernel, hardware, and any dependencies your scripts rely on. A consistent inventory helps you reproduce issues, plan upgrades, and ensure compatibility.
Start by collecting the Bash version. Run:
bash --version
Expected output on a typical Linux system:
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Record the major and minor version, as features and behavior vary. For example, associative arrays were introduced in Bash 4, and ${var@Q} quoting was added in Bash 4.4.
Next, gather operating system details. Use cat /etc/os-release or lsb_release -a if available:
cat /etc/os-release
Relevant lines might include:
NAME="Ubuntu"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 22.04.3 LTS"
VERSION_ID="22.04"
This tells you the distribution and release, which is important for package management and known issues.
Check the kernel version and architecture:
uname -a
Example output:
Linux prod-server-01 5.15.0-91-generic #101-Ubuntu SMP Tue Nov 14 13:30:08 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
Note the kernel version and architecture (x86_64, aarch64, etc.). Some Bash scripts may rely on specific kernel features or system calls.
List all external commands your scripts use, such as grep, awk, sed, curl, jq, and bc. Check their presence and versions:
for cmd in grep awk sed curl jq bc; do
if command -v $cmd >/dev/null 2>&1; then
echo "$cmd: $(command -v $cmd)"
else
echo "$cmd: MISSING"
fi
done
Example output:
grep: /usr/bin/grep
awk: /usr/bin/awk
sed: /usr/bin/sed
curl: /usr/bin/curl
jq: /usr/bin/jq
bc: /usr/bin/bc
If any required command is missing, install it or adjust your script. Document the exact versions using --version for each command, as syntax and options can change.
Also check the available disk space, memory, and CPU. Use df -h, free -h, and nproc:
df -h /
free -h
nproc
Example output:
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 98G 45G 48G 49% /
total used free shared buff/cache available
Mem: 15Gi 8.2Gi 3.1Gi 256Mi 4.2Gi 6.8Gi
Swap: 2.0Gi 0.0Gi 2.0Gi
8
This helps identify resource constraints that could affect script performance or cause failures.
Finally, record environment variables that may affect script behavior, especially PATH, LANG, and TZ:
echo "PATH=$PATH"
echo "LANG=$LANG"
echo "TZ=$TZ"
Example output:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LANG=en_US.UTF-8
TZ=UTC
Time zone and locale can cause subtle bugs in date parsing or sorting. Ensure they are consistent across all environments.
Compile all this information into a single inventory document or script. Keep it updated whenever the system changes. This baseline will be invaluable for troubleshooting and planning. Assign ownership of the inventory to a specific person, such as the lead operations engineer, and schedule a review every quarter or after any major system change.
Safe Configuration Path
Configuration changes are a common source of production incidents. To minimize risk, treat configuration as code: store it in version control, review changes, and apply them through a controlled process.
First, identify where your Bash scripts and their configuration files live. Common locations include /usr/local/bin for custom scripts, /etc for system-wide configuration, and application-specific directories. Use find to locate all Bash scripts on the system:
find / -type f -name "*.sh" 2>/dev/null
This may list many files. Narrow it down to directories relevant to your application.
For each script, determine how it reads configuration. Good practice is to use a separate configuration file rather than hardcoding values. For example, a script backup.sh might read /etc/backup/config.env:
#!/bin/bash
source /etc/backup/config.env
# ... rest of script
A configuration file might look like:
BACKUP_SOURCE="/var/www"
BACKUP_DEST="/mnt/backups"
RETENTION_DAYS=30
Store these configuration files in version control. Create a Git repository, for example ops-configs, and commit changes with meaningful messages. This provides an audit trail and easy rollback.
When changing configuration, always back up the current file first:
cp /etc/backup/config.env /etc/backup/config.env.bak.$(date +%Y%m%d)
Then edit and test the new configuration in a staging environment before production. If you don't have a full staging environment, at least run a syntax check and dry-run mode if the script supports it.
Use environment variables to override configuration when needed, but avoid scattering them. A common pattern is to have defaults in the script, overridden by a config file, and finally by environment variables:
#!/bin/bash
# Set defaults
BACKUP_SOURCE="/var/www"
BACKUP_DEST="/mnt/backups"
RETENTION_DAYS=30
# Load config file if exists
if [ -f /etc/backup/config.env ]; then
source /etc/backup/config.env
fi
# Environment variable overrides
BACKUP_SOURCE="${BACKUP_SOURCE_OVERRIDE:-$BACKUP_SOURCE}"
BACKUP_DEST="${BACKUP_DEST_OVERRIDE:-$BACKUP_DEST}"
RETENTION_DAYS="${RETENTION_DAYS_OVERRIDE:-$RETENTION_DAYS}"
This allows you to test with different values without editing files.
Another safe practice is to use set -u (or set -u -e -o pipefail) in scripts to catch unset variables and errors early. Add it near the top:
#!/bin/bash
set -euo pipefail
# script body
Explanation: -e exits on command failure, -u exits on unset variable, -o pipefail makes pipeline return non-zero if any command fails. Be careful with -e as it can cause unexpected exits if not all commands are expected to succeed; you can selectively disable it with set +e around commands that may fail safely.
When making changes, use a canary approach: apply to one server, verify, then roll out to the rest. For example, if you have servers web1, web2, web3, update web1 first, monitor for issues, then proceed. Designate a release manager to approve each rollout and document the decision in a change log.
Finally, document every configuration change in a change log. Include what was changed, why, and how to roll back. This is essential for incident response. Review the change log weekly to identify patterns or recurring issues.
Verification and Diagnostics
After any change, you must verify that the system works as expected. This section provides concrete checks and commands for common Bash production tasks.
Syntax Checking
Before running a script, check its syntax with bash -n:
bash -n /usr/local/bin/backup.sh
If the script has no syntax errors, there is no output. Otherwise, you'll see an error like:
/usr/local/bin/backup.sh: line 15: syntax error near unexpected token `fi'
Always run this after editing.
Linting
Use shellcheck to catch common issues:
shellcheck /usr/local/bin/backup.sh
Example warning:
In /usr/local/bin/backup.sh line 10:
if [ $RETENTION_DAYS -gt 30 ]; then
^-- SC2086: Double quote to prevent globbing and word splitting.
Fix warnings to improve script robustness.
Dry Run
Many scripts support a dry-run mode to show what they would do without executing. Implement this with a --dry-run flag or a DRY_RUN environment variable. For example:
#!/bin/bash
DRY_RUN="${DRY_RUN:-false}"
if [ "$DRY_RUN" = "true" ]; then
echo "Would delete files older than $RETENTION_DAYS days from $BACKUP_DEST"
else
find "$BACKUP_DEST" -type f -mtime +$RETENTION_DAYS -delete
fi
Run a dry run before actual execution:
DRY_RUN=true ./backup.sh
Expected output:
Would delete files older than 30 days from /mnt/backups
Functional Testing
After running a script, verify its effects. For a backup script, check that the backup file was created and has a reasonable size:
ls -lh /mnt/backups/
Example output:
total 2.3G
-rw-r--r-- 1 root root 2.3G Dec 20 02:00 backup-2024-12-20.tar.gz
Then test restoration by extracting to a temporary directory:
tar -tzf /mnt/backups/backup-2024-12-20.tar.gz | head
This lists the contents without extracting, verifying the archive is valid.
Log Monitoring
Ensure your scripts log their activities. Check that logs are being written correctly. For example, if your script logs to /var/log/backup.log, tail it:
tail -f /var/log/backup.log
Look for error messages or unexpected warnings.
Process and Resource Checks
If your script runs as a daemon or cron job, verify it is running and not consuming excessive resources. Use ps and top:
ps aux | grep backup.sh
Example output:
root 1234 0.1 0.2 123456 7890 ? S 02:00 0:01 /bin/bash /usr/local/bin/backup.sh
Check CPU and memory usage with top -p 1234.
Network Connectivity
For scripts that interact with network services, test connectivity. For example, if your script uploads backups to a remote server, use curl to test the endpoint:
curl -I https://backup.example.com
Expected output includes HTTP response headers; a 200 OK indicates success.
Scheduled Jobs
For cron jobs, verify they are scheduled correctly:
crontab -l
Example output:
0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
Check cron logs to ensure the job ran. On systems with systemd, you can use journalctl -u cron or systemctl status cron.
Configuration Verification
After changing configuration, test that the script picks up the new values. For example, add a temporary echo at the beginning of the script to print variables, or use bash -x to trace execution:
bash -x /usr/local/bin/backup.sh
This prints each command before execution, showing variable values. Look for the expected values.
Failure Modes and Recovery
Even with careful planning, failures happen. This section covers common failure modes in Bash production systems and how to recover.
Common Failure Modes
- Syntax errors: Cause immediate script failure. Prevented by
bash -nchecks. - Unset variables: Lead to wrong behavior or errors. Prevented by
set -u. - Command not found: Missing dependency or PATH issue. Prevented by environment inventory and dependency checks.
- Permission denied: Script lacks execute permission or file access. Check with
ls -landchmod. - Disk full: Backups or logs fill the disk. Monitor disk usage and set up alerts.
- Network failures: Remote servers unreachable. Add retries and timeouts.
- Race conditions: Two instances of the script run simultaneously. Use lock files.
- Data corruption: Partial writes or interrupted transfers. Use checksums and atomic operations.
Recovery Procedures
For each failure mode, have a documented recovery procedure. Assign a primary owner for each procedure and review them quarterly. Examples:
Syntax Error Recovery
If a script fails with a syntax error after deployment, immediately revert to the previous version. If using version control, checkout the last known good commit:
git checkout <commit-hash> -- backup.sh
Then redeploy.
Disk Full Recovery
If disk is full, first identify large files:
du -ah / | sort -rh | head -20
This lists the 20 largest files/directories. Clean up old logs, temporary files, or unnecessary backups. For example, delete files older than 7 days in /tmp:
find /tmp -type f -mtime +7 -delete
Then verify space with df -h.
Network Failure Recovery
If a script depends on a remote service and it fails, implement retries. Example with curl:
curl --retry 5 --retry-delay 10 --retry-all-errors -o backup.tar.gz https://example.com/backup.tar.gz
This retries 5 times with 10-second delays on any error. If still fails, alert and exit non-zero.
Lock File Recovery
To prevent race conditions, use a lock file. Example implementation:
#!/bin/bash
LOCKFILE=/var/run/backup.lock
if [ -f $LOCKFILE ]; then
echo "Another instance is running" >&2
exit 1
fi
touch $LOCKFILE
trap 'rm -f $LOCKFILE' EXIT
# main logic
If a previous run crashed without removing the lock, you may need to manually remove it:
rm /var/run/backup.lock
But first ensure no actual process is running.
Data Corruption Recovery
To detect corruption, use checksums. Generate a checksum for a backup file:
sha256sum backup.tar.gz > backup.tar.gz.sha256
Verify:
sha256sum -c backup.tar.gz.sha256
Expected output:
backup.tar.gz: OK
If corrupted, restore from a known good copy or re-run the backup.
Rollback
Always have a rollback plan for configuration and code changes. Keep backups of previous versions. For scripts, retain old versions with a naming convention like backup.sh.20240101. For configuration, keep the .bak files created earlier.
To rollback a script:
cp /usr/local/bin/backup.sh /usr/local/bin/backup.sh.broken.$(date +%s)
cp /usr/local/bin/backup.sh.20240101 /usr/local/bin/backup.sh
chmod +x /usr/local/bin/backup.sh
Then verify with bash -n and run tests.
Monitoring and Alerting
Set up monitoring to detect failures early. Monitor disk space, CPU, memory, and script exit codes. For cron jobs, you can wrap them in a script that sends an alert on non-zero exit. For example:
#!/bin/bash
/usr/local/bin/backup.sh
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "Backup failed with exit code $STATUS" | mail -s "Backup Failed" [email protected]
fi
Consider using monitoring tools like Nagios, Zabbix, or Prometheus with alerting rules.
Common Pitfalls and How to Avoid Them
Even experienced operators make mistakes. Here are common pitfalls in Bash production operations and how to prevent or recover from them.
Pitfall 1: Not Quoting Variables
Unquoted variables can cause word splitting and globbing, leading to unexpected behavior. For example:
file="my file.txt"
rm $file # This becomes: rm my file.txt (two arguments)
Why it happens: Developers forget that Bash splits unquoted variables on spaces and expands globs.
How to avoid: Always quote variables: rm "$file". Use shellcheck to catch these.
Pitfall 2: Using set -e Incorrectly
set -e exits on any command failure, but it can cause scripts to exit prematurely if a command is expected to fail (e.g., grep not finding a match).
Why it happens: Strict error handling can be too rigid.
How to avoid: Use set -e but selectively disable with set +e around commands that may fail, or use || true for expected failures:
grep "pattern" file || true
Pitfall 3: Not Cleaning Up Temporary Files
Scripts that create temporary files may leave them behind, filling disk space.
Why it happens: Missing cleanup logic or interrupted execution.
How to avoid: Use trap to remove temporary files on exit:
TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"' EXIT
Pitfall 4: Hardcoding Paths and Values
Hardcoded paths make scripts less portable and harder to maintain.
Why it happens: Quick and dirty scripting.
How to avoid: Use variables and configuration files. For example:
BACKUP_DEST="/mnt/backups" # Define once at top
Pitfall 5: Ignoring Exit Codes
Ignoring exit codes can hide failures. For example, command1; command2 runs command2 even if command1 fails.
Why it happens: Oversight.
How to avoid: Check exit codes explicitly or use set -e. For critical commands, handle failures:
if ! command1; then
echo "command1 failed"
exit 1
fi
Pitfall 6: Not Testing in Staging
Deploying untested scripts to production can cause outages.
Why it happens: Time pressure or lack of staging environment.
How to avoid: Always have a staging environment that mirrors production as closely as possible. Run syntax checks, linting, and dry runs before deployment.
Pitfall 7: Poor Logging
Insufficient logging makes troubleshooting difficult.
Why it happens: Not prioritizing logging.
How to avoid: Log key actions and errors with timestamps:
echo "$(date): Starting backup" >> /var/log/backup.log
Use a logging function with levels.
Operations Checklist
This section provides a repeatable checklist for day-to-day Bash operations. Follow these steps regularly to maintain system health and reduce incidents. Assign a specific owner for each checklist item and review the checklist itself monthly to ensure it stays relevant.
Daily Operations
- [ ] Check that critical cron jobs ran successfully. Review logs for errors using
grep -i error /var/log/backup.logor system logs. Owner: On-call operator. - [ ] Monitor disk space with
df -h. Alert if usage exceeds 80%. Owner: Monitoring team. - [ ] Check system load with
uptimeand memory withfree -h. Ensure no excessive load. Owner: On-call operator. - [ ] Verify network connectivity for scripts that rely on remote services. Test with
curl -Iorping. Owner: Network administrator. - [ ] Review any error emails from scripts. Owner: Script maintainer.
Weekly Operations
- [ ] Run file system checks (e.g.,
fsckon unmounted volumes if possible; otherwise schedule for maintenance window). Owner: System administrator. - [ ] Rotate logs. Ensure logrotate is configured for your script logs. Check
/etc/logrotate.d/for entries. Owner: System administrator. - [ ] Test backups by restoring a sample file to a temporary location. Verify integrity with checksums. Owner: Backup administrator.
- [ ] Check for security updates:
apt list --upgradable(Debian/Ubuntu) oryum check-update(RHEL/CentOS). Apply as per change management. Owner: Security officer. - [ ] Review script permissions and ownership to ensure least privilege:
ls -l /usr/local/bin/*.sh. Owner: Security officer.
Monthly Operations
- [ ] Full system audit: list all Bash scripts and their purposes. Check for orphaned scripts. Owner: Lead operations engineer.
- [ ] Review configuration files for unused variables or deprecated options. Owner: Script maintainers.
- [ ] Test disaster recovery plan: simulate a failure (e.g., delete a backup file) and restore. Owner: Disaster recovery coordinator.
- [ ] Update documentation, including this checklist if needed. Owner: Documentation lead.
- [ ] Check Bash version and consider if upgrade is needed for security or features. Plan upgrade in staging first. Owner: System administrator.
Quarterly Operations
- [ ] Conduct a performance review: measure script execution times, identify bottlenecks. Owner: Performance engineer.
- [ ] Review access controls: who can modify scripts and configurations? Remove unnecessary access. Owner: Security officer.
- [ ] Archive old logs and backups per retention policy. Delete files older than policy. Owner: Backup administrator.
- [ ] Test failover to a backup server if applicable. Owner: Disaster recovery coordinator.
Annual Operations
- [ ] Full disaster recovery drill: restore critical systems from backups in an isolated environment. Owner: Disaster recovery coordinator.
- [ ] Review entire Bash infrastructure: are there better tools or approaches? (e.g., converting complex scripts to a modern language if warranted, but only after careful evaluation). Owner: Architecture team.
- [ ] Renew any certificates or credentials used by scripts. Owner: Security officer.
- [ ] Update the operations runbook with any changes made during the year. Owner: Documentation lead.
Practical Example: Backup Script Checklist
Here is a specific checklist for operating a backup script. Assign an owner for each step and review the checklist monthly.
- Pre-run: Verify source and destination mounts are available (
mount | grep /mnt/backups). Check sufficient disk space on destination. Owner: Backup operator. - Execution: Run script with
--dry-runfirst if supported. Then run actual backup. Monitor progress if long-running. Owner: Backup operator. - Post-run: Check exit code (
$?). Verify backup file exists and size is plausible (ls -lh). Compute checksum and store. Check log for errors. Test restore of a few files. Owner: Backup operator. - Weekly: Test full restore to a temporary directory and compare file counts. Owner: Backup administrator.
- Monthly: Review retention policy; delete old backups per policy. Archive monthly backups to offsite storage. Owner: Backup administrator.
Use this checklist as a starting point and customize it for your environment. Print it or integrate into your ticketing system.
Conclusion
Operating Bash scripts in production requires discipline and a systematic approach. By maintaining a thorough environment inventory, applying configuration changes safely, verifying behavior with concrete diagnostics, preparing for failures, and following a repeatable operations checklist, you can significantly reduce downtime and improve reliability.
Start with the basics: inventory your systems, establish version control for scripts and configuration, and set up monitoring and alerting. Then, implement the daily, weekly, and monthly checklists. Remember to test changes in staging, use rollback procedures, and continuously document your environment.
These practices will help your team run Bash-based systems with confidence, knowing that you have the tools and processes to detect, diagnose, and recover from issues quickly.