Advertisement
Rnery

swapoff

Mar 1st, 2022 (edited)
787
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.61 KB | Source Code | 1 0
  1. #!/usr/bin/env bash
  2.  
  3. free_memory=$(free -m -l -t -h | awk '/Mem/ {print $4}')
  4.  
  5. create_swap_if_needed() {
  6.   if [[ $free_memory == 0 ]]; then
  7.     echo "Creating swap file..."
  8.     sudo sh -c "
  9.      swapoff
  10.      dd if=/dev/zero of=/swapfile bs=1G count=4 status=progress; sync
  11.      mkswap /swapfile
  12.      swapon /swapfile
  13.    "
  14.   fi
  15.   echo "$free_memory"
  16. }
  17.  
  18. check_for_reboot() {
  19.   if [[ $free_memory == 0 ]]; then
  20.     echo "Free memory is 0, rebooting..."
  21.     sudo reboot
  22.   else
  23.     echo "Free memory is sufficient."
  24.   fi
  25. }
  26.  
  27. main() {
  28.   free_memory=$(create_swap_if_needed)
  29.   check_for_reboot
  30. }
  31.  
  32. main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement