×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Bash
Posted by: Roman Ignatov
Added: Nov 22, 2016 4:38 PM
Views: 9
Tags: sysadmin
  1. #!/bin/bash
  2.  
  3. free_data="$(free)"
  4. mem_data="$(echo "$free_data" | grep 'Mem:')"
  5. free_mem="$(echo "$mem_data" | awk '{print $4}')"
  6. buffers="$(echo "$mem_data" | awk '{print $6}')"
  7. cache="$(echo "$mem_data" | awk '{print $7}')"
  8. total_free=$((free_mem + buffers + cache))
  9. used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"
  10.  
  11. echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"
  12. if [[ $used_swap -eq 0 ]]; then
  13.     echo "Congratulations! No swap is in use."
  14. elif [[ $used_swap -lt $total_free ]]; then
  15.     echo "Freeing swap..."
  16.     sudo swapoff -a
  17.     sudo swapon -a
  18. else
  19.     echo "Not enough free memory. Exiting."
  20.     exit 1
  21. fi