文章截取自: 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).
Manually
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:
1 2 3 4 5 |
# truncate -s 0 /swapfile # chattr +C /swapfile # btrfs property set /swapfile compression none |
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:
1 2 3 |
# fallocate -l 512M /swapfile |
Note: fallocate may cause problems with some file systems such as F2FS.[1] As an alternative, using dd is more reliable, but slower:
1 2 3 |
# dd if=/dev/zero of=/swapfile bs=1M count=512 status=progress |
Set the right permissions (a world-readable swap file is a huge local vulnerability):
1 2 3 |
# chmod 600 /swapfile |
After creating the correctly sized file, format it to swap:
1 2 3 |
# mkswap /swapfile |
Activate the swap file:
1 2 3 |
# swapon /swapfile |
Finally, edit the fstab configuration to add an entry for the swap file:
1 2 3 |
/etc/fstab |
1 2 3 |
/swapfile none swap defaults 0 0 |
For additional information, see fstab#Usage.
Remove swap file
To remove a swap file, it must be turned off first and then can be removed:
1 2 3 4 |
# swapoff /swapfile # rm -f /swapfile |
Finally remove the relevant entry from /etc/fstab.
Automated
systemd-swap
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.conf. Start/enable the systemd-swap service.
Visit the authors GitHub page for more information and setting up the recommended configuration.