Skip to content

Instantly share code, notes, and snippets.

@cristianbica
Last active August 29, 2015 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristianbica/10347658 to your computer and use it in GitHub Desktop.
Save cristianbica/10347658 to your computer and use it in GitHub Desktop.
Creates swap file on linux
# Usage:
# curl -s https://gist.githubusercontent.com/cristianbica/10347658/raw/setup_swap.rb | sudo ruby - multiplier [remove_current_swap]
# multiplier - when creating the swap will multiply the current RAM with the multiplier
# remove_current_swap - true to remove current swap in /swapfile (default false)
# Ex: curl -s https://gist.githubusercontent.com/cristianbica/10347658/raw/setup_swap.rb | sudo ruby - 2
# Ex: curl -s https://gist.githubusercontent.com/cristianbica/10347658/raw/setup_swap.rb | sudo ruby - 2 true
if ARGV[1] and ARGV[1]=="true"
puts "Removing swap from swapfile as requested ..."
`swapoff /swapfile`
`rm -rf /swapfile`
`sed -i".bak" '/swapfile/d' /etc/fstab`
puts "DONE"
end
if File.exists?("/swapfile")
puts "/swapfile exists. Exiting"
else
multiplier = (ARGV[0] || 2).to_f
`cat /proc/meminfo | grep MemTotal` =~ /(\d+)/
current_ram = $1.to_i*1024
swapsize = (current_ram*multiplier).to_f
puts "Creating a swapfile of #{(swapsize/1024/1024/1024).round(2)}G .."
`fallocate -l #{swapsize.to_i} /swapfile`
`chmod 600 /swapfile`
`mkswap /swapfile`
`swapon /swapfile`
`echo '/swapfile none swap defaults 0 0' >> /etc/fstab`
puts "DONE"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment