Linux swap with dphys-swapfile

This is a solution for a , some without swap of some machine setup without swap where you need swap for something without wanting to fiddle with the drive partitions or so.

This is a quick and dirty “short manual” for based environments (such as , or ).

First run this:

cat > dphys-swap.sh << EOF
#!/bin/bash
#~/up
apt-get install dphys-swapfile
echo "CONF_SWAPSIZE=2048"|tee -a /etc/dphys-swapfile
dphys-swapfile setup
dphys-swapfile swapon
systemctl restart dphys-swapfile.service
systemctl status dphys-swapfile.service
free -h
EOF

This will just create a short with the needed commands to run to get setup and running. Please alter the number 2048 to your need, it is the size of the swap memory that will be setup. The size of the swap should most likely by equal to the real memory installed, sometimes twice the size seems to be a good choice too.

If you don’t know your memory size you can find it out by running the command “free -h”, which will print the size of the physical memory installed and the below this the swap size(s).

After pasting the above code into your shell, which will create a file called “dphys-swap.sh” in the current folder (you should be in your home folder!!), you need to make the shell script “dphys-swap.sh” executable by running:

chmod +x dphys-swap.sh

Then you need to run the script like this:

sudo ~/dphys-swap.sh

It will ask for some confirmation(s) to install certain packages.

The last commands will output the status of the systemd service “dphys-swapfile.service” and the last line will show you the memory and swap size again.

Remark:
In the script above I use “up”, my full update of the system. I just blogged that one too, have a look here.