single line power : create a swap file in linux
Posted on January 26, 2017 • 1 minutes • 177 words • Suggest Changes
In case the machine has no swap, (VPS are typical clients but also containers) you can just create a file and assign it to be used as swap. So here is the magic line : (this creates a 512mb swapfile)
dd if=/dev/zero of=/swapfile bs=1024 count=512k && chown root:root /swapfile && chmod 0600 /swapfile && mkswap /swapfile -f && swapon /swapfile
In steps ? OK :
(1) create an file filled with zero’s of 1024*512k = 512M
dd if=/dev/zero of=/swapfile bs=1024 count=512k
(2) make user:group both root
chown root:root /swapfile
(3) only allow read/write (2+4) on the file
chmod 0600 /swapfile
(4) prepare this file for swap usage
mkswap /swapfile -f
(5) tell the kernel a new swap location is ready for use
swapon /swapfile
(6) not in the single line but you should also add this file to /etc/fstab in case it reboots
/swapfile none swap sw 0 0
two remarks :
- Don’t use this on desktops to hibernate
- SSD’s won’t like that kind of file, prefer not to place it on SSD’s if you can chose.