Skip to content

Instantly share code, notes, and snippets.

@kendrickjr
Created January 11, 2023 20:03
Show Gist options
  • Save kendrickjr/fc2108f1ffb2330f193f823b562963f9 to your computer and use it in GitHub Desktop.
Save kendrickjr/fc2108f1ffb2330f193f823b562963f9 to your computer and use it in GitHub Desktop.
linux server maintanance script

Here's an example of a simple bash script that can be used to perform some basic maintenance tasks on a Linux server:

#!/bin/bash

# Update package list and upgrade installed packages
apt-get update && apt-get upgrade -y

# Remove unnecessary packages and dependencies
apt-get autoremove -y

# Clear the package cache to free up disk space
apt-get clean

# Check and repair any file system errors
fsck -Af -M

# Clear the system log files
cat /dev/null > /var/log/syslog
cat /dev/null > /var/log/auth.log

# Clear the bash history
cat /dev/null > ~/.bash_history && history -c

# Check the server load 
uptime

# Check the service status and restart if it is down
systemctl list-units --type=service --all | grep inactive | awk '{print $2}' | while read line; do systemctl start $line; done

This script performs several basic maintenance tasks, such as updating and upgrading installed packages, removing unnecessary packages and dependencies, clearing the package cache, checking and repairing file system errors, clearing system log files, clearing the bash history, checking the server load and the services that might have been inactive and restarting them.

It's a good practice to schedule this script to run automatically using the cron job.

crontab -e

Then add the below line to schedule the backup everyday at 1AM

0 1 * * * /path/to/script/maintenance.sh

You might also want to customize and adjust the script as per your needs and your server's specific configurations and requirements. Also, it's recommended to test the script in a development environment before deploying it to your production server, to make sure that it does not cause any issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment