how do I clear the swap? I know it isn't something that is needed, but I still want to know how to do it. this is what I'm doing so far:

# to check if there is enough space in ram for the swap contents:
free -m
sudo swapoff -a
sudo chmod 600 /var/swap
sudo mkswap /var/swap
sudo swapon -a

that works for clearing the swap, but it doesn't turn on again because it isn't being used until I reboot.

  • 1
    What turns off swap is swapoff -a. Since you already know that I'm not clear what it is that you're asking Commented Feb 6, 2021 at 15:55
  • @roaima first of all my question is how to clear it. and when I turn it back on it doesn't work. Commented Feb 6, 2021 at 16:00
  • Are you asking "why does swap not turn on after clearing it? Am I doing it right? I want to clear it then continue using it." Commented Feb 6, 2021 at 22:09
  • @ctrl-alt-delor yes, that's exactly what I'm asking. I already got a answer though. Commented Feb 6, 2021 at 23:19

2 Answers 2


1. Without systemd

You can disable swap with swapoff -a. If swap is being used it is not an instantaneous action (see man swapoff).

If you have defined swap in /etc/fstab you can use swapon -a to activate all known swap files and partitions. If none is defined there you need to declare the swap space that you want to use, for example swapon /var/swap.

There is no need to recreate it each time you want to use it

2. With systemd

The new method for activating swap is through a systemd service, run at boot. You can see its status, for example,

systemctl status dphys-swapfile     # What happened last time it ran
systemctl restart dphys-swapfile    # Recompute the swapfile space and reactivate it

In turn, systemd calls the dphys-swapfile command (see man dphys-swapfile), which computes a reasonably sized swapfile partition and activates it, or deactivates it, as required.

For example,

dphys-swapfile swapoff    # Stop using the swapfile
dphys-swapfile setup      # (Re-)compute an optimal swap space as /var/swap
dphys-swapfile swapon     # Start using the computed swapfile

In the systemd and dphys-swapfile world, swapspace defaults to the file /var/swap rather than a partition


You are almost there. Before clearing swap, you must unmount it first. In most cases, swap is already defined in the /etc/fstab file. Follow these steps to avoid rebooting your system:

sudo swapoff -a
sudo umount /var/swap
sudo chmod 600 /var/swap
sudo mkswap /var/swap
sudo swapon -a
sudo mount -a 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .