Power User: 10 Useful Bash Functions to Monitor and Maintain your Linux Server

Power User: 10 Useful Bash Functions to Monitor and Maintain your Linux Server

Using Bash functions in your Linux server administration can help automate repetitive tasks, making your work more efficient.

Here are 10 useful Bash functions tailored to help you monitor and maintain your Linux server more effectively:

  1. Check Disk Usage:
    A function to check the disk usage of the specified directory.
   function check_disk_usage() {
       du -sh "$1"
   }
  1. Update System:
    Automates the process of updating system packages.
   function update_system() {
       sudo apt update && sudo apt upgrade -y
   }
  1. Backup Directory:
    Compresses and backs up a specified directory.
   function backup_dir() {
       tar -czf "$2" "$1"
       echo "Backup of $1 completed and saved to $2"
   }
  1. Monitor Top Processes:
    Shows top processes by CPU or memory usage.
   function top_cpu() {
       ps -eo %cpu,%mem,pid,comm --sort=-%cpu | head -10
   }

   function top_mem() {
       ps -eo %cpu,%mem,pid,comm --sort=-%mem | head -10
   }
  1. Check Service Status:
    Checks the status of a given service.
   function check_service() {
       systemctl status "$1" | grep "Active"
   }
  1. Restart Service:
    Restarts a specified service.
   function restart_service() {
       sudo systemctl restart "$1"
       echo "$1 service restarted."
   }
  1. Add User to Sudoers:
    Adds a specified user to the sudoers group.
   function add_sudoer() {
       sudo usermod -aG sudo "$1"
       echo "$1 added to sudoers."
   }
  1. Check Open Ports:
    Lists open network ports and associated processes.
   function check_ports() {
       sudo netstat -tulpn | grep LISTEN
   }
  1. Find Large Files:
    Finds files larger than a specified size in a directory.
   function find_large_files() {
       find "$1" -type f -size +"$2" -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
   }
  1. Log File Tailer:
    Tails the last few lines of a specified log file and monitors for changes.
    bash function tail_log() { tail -f "$1" }

To use these functions, you can add them to your ~/.bashrc file. After adding the functions, you’ll need to reload the file with the command source ~/.bashrc to make them available in your session. These functions will help you perform routine server management tasks more efficiently, freeing up time for other critical server administration activities.

Leave a Reply

Your email address will not be published. Required fields are marked *


Translate ยป