Creating the swap file
To begin with, before creating a swap file, it is advisable to check the list of mounted partitions and their size. To do this, execute the df -h command.
In this example, a swap file will be created in the /var directory with a size of 4GB.
- Creating a swap file
sudo touch /var/.swap.img sudo chmod 600 /var/.swap.img - We fill the file with zeros to the desired size. In this example, the swap size will be 4GB
sudo dd if=/dev/zero of=/var/.swap.img bs=1024k count=4096 - Format the swap file as swap space
sudo mkswap /var/.swap.img - Activate the swap file
sudo swapon /var/.swap.img - To make the swap file persistent across reboots, add it to the /etc/fstab file
sudo echo "/var/.swap.img none swap sw 0 0" >> /etc/fstab - Verify that the swap file is active and working correctly by using the free command or the swapon command:
free -hor
swapon --show
The swap file will now provide additional virtual memory to your system, which can be beneficial for managing memory-intensive tasks.
