How to delete a swap file in Ubuntu?

I created a swap file in Ubuntu by following this process, but I no longer need it, so I would like to delete it.

However, the blog article doesn't write anything regarding the deletion, so I tried deleting it via sudo rm -rf, but it got the Operation not permitted error.

So far, I tried many answers to how to delete a file with the same error, but nothing worked in my case:

  • https://unix.stackexchange.com/questions/370255/as-root-cannot-remove-file-under-tmp-operation-not-permitted
  • Changing Ownership: "Operation not permitted" - even as root!
  • https://unix.stackexchange.com/questions/29902/unable-to-delete-file-even-when-running-as-root

, which include:

  • change the permission of both the swapfile and the root directory / (hmod ugo+w .)
  • change the immutable flag on both the swapfile and / (chattr -i -a .)
  • reboot the system

All of them didn't work. I wonder how I can delete it, but if it is a swap file, how can I delete it?

The result of free -h is:

              total        used        free      shared  buff/cache   available 
Mem:           1.7G        101M        405M        1.2M        1.2G        1.4G
Swap:          1.5G        234M        1.3G

Solution 1:

The output of free -h indicates that swap is being used - the swap process is still running.

Enter the command

sudo swapoff /path/to/swapfile/to/be/deleted

This will disable the swapfile, and the file can be deleted at that point.

Please note that if you have created an entry in /etc/fstab for the swapfile, you should also delete it (or comment it out by adding # at the beginning of the line).