Swap space in Linux acts as overflow for physical RAM, providing additional virtual memory when running many processes or memory‑intensive workloads. A swap file created on an existing filesystem avoids repartitioning disks and can be convenient on virtual machines or cloud instances. When that swap file is no longer required, removing it frees disk space and simplifies resource planning.
The kernel’s virtual memory subsystem moves less frequently used pages from RAM into swap space, which may live on a dedicated partition or on a regular file marked and activated as swap. Swap files are typically referenced in /etc/fstab so they are enabled automatically at boot with swapon. Cleaning up a swap file requires deactivating it at runtime and removing any persistent configuration so it is not silently recreated.
Disabling a swap file on a system with limited RAM can increase the risk of out‑of‑memory conditions under heavy load, causing processes to be killed or the system to become unresponsive. Checking current memory and swap usage before proceeding reduces the chance of surprising failures. Safe removal assumes shell access with sudo privileges and applies only to swap files, not to swap partitions, which must be handled with different steps.
$ whoami root $ groups root
Being in the sudo group or an equivalent administrative group allows privileged commands required for swap management.
$ swapon --show NAME TYPE SIZE USED PRIO /var/lib/swap file 1024M 0B -2 /mnt/data/swapfile file 64M 0B -3
The NAME column lists each active swap device or file and shows whether a swap file such as /mnt/data/swapfile is in use.
$ free -h
total used free shared buff/cache available
Mem: 23Gi 1.3Gi 20Gi 13Mi 1.6Gi 21Gi
Swap: 1.1Gi 0B 1.1Gi
High Swap usage under normal load can indicate that removing the swap file may cause out‑of‑memory conditions and process termination.
$ sudo swapoff /mnt/data/swapfile
The command returns no output when the swap file is successfully deactivated.
$ swapon --show NAME TYPE SIZE USED PRIO /var/lib/swap file 1024M 0B -2
On systems with multiple swap areas, ensure the swap file path disappears from the list.
$ grep swapfile /etc/fstab 2:/mnt/data/swapfile none swap sw 0 0 $ sudo sed -i "/\\/mnt\\/data\\/swapfile none swap sw 0 0/d" /etc/fstab
Editing with sed or a text editor achieves the same result; the key is to delete the line referencing the swap file.
$ sudo rm /mnt/data/swapfile $ sudo umount /mnt/data $ sudo losetup -d /dev/loop0 $ sudo rm /root/sg-work/swapfs.img
Confirm the paths carefully before removing files or detaching loop devices to avoid deleting unrelated data.
$ swapon --show NAME TYPE SIZE USED PRIO /var/lib/swap file 1024M 0B -2 $ grep swapfile /etc/fstab
Absence of the swap file path in both commands confirms that the swap file has been fully removed from runtime state and persistent configuration.