single line power : create a swap file in linux

Posted 26 January, 2017

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.

If you enjoyed this article, please consider buying me a Dr Pepper.
Fuel the beast!

Buy me a Dr PepperBuy me a Dr Pepper

Show Comments (0)
© SvennD