How to expand existing swap file?

6,899

Resizing the file is the same process as making a swap file. So, you have three options:

  1. Add another swapfile. 2 files of 2GB is the same as one of 4GB (ie 4GB swap)
  2. Delete this file. and make a new one that is 4GB
  3. Reuse this file.

To make new or reuse your current file, you have to type:

sudo swapoff -a   # turn off all swap
sudo rm /swapfile # this step is if you want to delete the current file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 #makes a 4GB file
sudo chmod 600 /swapfile #set permission to root only if you made a new file
sudo mkswap /swapfile #converts file to swap format
sudo swapon /swapfile #enable swap on the file.

Note: if you are also using a swap partition it will have to be enabled also.

If you just want to add another 2GB file then:

sudo dd if=/dev/zero of=/swapfile2 bs=1M count=2048 #makes a 2GB file
sudo chmod 600 /swapfile2 #set permission to root only
sudo mkswap /swapfile2 #converts file to swap format
sudo swapon /swapfile2 #enable swap on the file.

Then edit /etc/fstab. Duplicate the entry for your current swapfile, and change the filename to the new file (swapfile2).

Share:
6,899
Linuxios
Author by

Linuxios

Updated on September 18, 2022

Comments

  • Linuxios
    Linuxios over 1 year

    I'm running Kubuntu 17.10, upgraded from 17.04 in-place.

    I have a 2GB swap file on my SSD that was created by the installer when I first installed 17.04. Here's the contents of /proc/swaps (fresh after a reboot from running out of memory):

    Filename                                Type            Size    Used    Priority
    /swapfile                               file            2097148 0       -1
    

    How can I expand this swapfile to 4GB? I've found plenty of answers about resizing swap partitions and adding new swap files, but nothing about resizing existing ones.

  • PerlDuck
    PerlDuck about 6 years
    I think in the second case (two files) you also need to add a line to /etc/fstab.
  • ravery
    ravery about 6 years
    @PerlDuck -- yes, I think you are right.
  • PerlDuck
    PerlDuck about 6 years
    Actually I didn't know we can have more than one swapfile or -partition.
  • ravery
    ravery about 6 years
    @PerlDuck -- yes, there can be more than one file and/or partition; even a combination of the two. Hibernating requires a partition, unless you do some fancy system settings to make it use a file.
  • Linuxios
    Linuxios about 6 years
    Thanks for the answer -- I wonder, is it worth adding the faster alternative of using fallocate from @PerlDuck's link? Also, should the command from the same to set permissions on the swap file also be included?
  • Linuxios
    Linuxios about 6 years
    @ravery: When I ran mkswap it actually came back with insecure permissions 0644, 0600 suggested., but it didn't change them itself, I still had to.