Swap File

文章截取自: https://wiki.archlinux.org/index.php/Swap#Manually


Swap file

As an alternative to creating an entire partition, a swap file offers the ability to vary its size on-the-fly, and is more easily removed altogether. This may be especially desirable if disk space is at a premium (e.g. a modestly-sized SSD).

Warning: Btrfs supports swap file with limitations since Linux kernel version 5.0. See Btrfs#Swap file for more information.


Swap file creation

For copy-on-write file systems like Btrfs, first create a zero length file, set the  No_COW attribute on it with chattr, and make sure compression is disabled:

See Btrfs#Swap file for more information.

Use  fallocate to create a swap file the size of your choosing (M = Mebibytes, G = Gibibytes). For example, creating a 512 MiB swap file:

Note: fallocate may cause problems with some file systems such as F2FS.[1] As an alternative, using dd is more reliable, but slower:

Set the right permissions (a world-readable swap file is a huge local vulnerability):

After creating the correctly sized file, format it to swap:

Activate the swap file:

Finally, edit the fstab configuration to add an entry for the swap file:

For additional information, see fstab#Usage.

Note: The swap file must be specified by its location on the file system not by its UUID or LABEL.

Remove swap file

To remove a swap file, it must be turned off first and then can be removed:

Finally remove the relevant entry from  /etc/fstab.



systemd-swap is a script for creating hybrid swap space from zram swaps, swap files and swap partitions. It is not affiliated with the systemd project.

Install the systemd-swap package. Set  swapfc_enabled=1 in the Swap File Chunked section of  /etc/systemd/swap.confStart/enable the  systemd-swap service.

Visit the authors GitHub page for more information and setting up the recommended configuration.

Note: If the journal keeps showing the following warning  systemd-swap[..]: WARN: swapFC: ENOSPC and no swap file is being created, you need to set  swapfc_force_preallocated=1 in  /etc/systemd/swap.conf.