Linux Swap Details
Swap space in Linux is a dedicated area on the disk used as virtual memory when the system's physical RAM is fully utilized. It helps prevent out-of-memory errors by temporarily moving inactive pages from RAM to the swap space.
Steps to Create a Swap Partition
- Check available disk space using the command:
lsblk - Create a swap partition using
fdiskorparted. - Format the partition as swap space:
mkswap /dev/sdX(replace/dev/sdXwith your partition). - Enable the swap space:
swapon /dev/sdX. - Make the swap space permanent by adding it to
/etc/fstab:/dev/sdX none swap sw 0 0
Example
Here is an example of creating a swap partition:
# Create a 1GB swap file using our particular disk
sudo mkswap /dev/sdb1
# Enable the swap file
sudo swapon /dev/sdb1
# Verify the swap is active
swapon --show
# Add to /etc/fstab for persistence
echo '/dev/sdb1 none swap sw 0 0' | sudo tee -a /etc/fstab
Creating SWAP partition using dd Command
Alternatively, you can create a swap file using the dd command:
# Create a 1GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1G count=1
# Set the correct permissions
sudo chmod 600 /swapfile
# Format the file as swap
sudo mkswap -v1 -f /swapfile
# Enable the swap file
sudo swapon /swapfile
# Verify the swap is active
swapon --show
# Add to /etc/fstab for persistence
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Checking Swap Usage
To check the current swap usage, use the command:
free -h
Or view detailed swap information:
swapon --show
Removing Swap Space
To remove a swap partition or file, first disable it:
sudo swapoff /dev/sdX
Then, remove the entry from /etc/fstab if it was added there. Finally, you can delete the swap file or partition using:
sudo rm /swapfile
sudo fdisk /dev/sdX
# Follow the prompts to delete the partition
Always ensure you have sufficient RAM before removing swap space, as it can lead to system instability if the RAM is fully utilized.