mkswap Command Cheat Sheet
mkswap sets up a Linux swap area on a device or in a file. Swap space is used when physical RAM is full.
Synopsis
mkswap [options] device [size]
Swap on Partition
- Create partition (Type 82 - Linux Swap) via
fdiskorgdisk. - Format as swap:
sudo mkswap /dev/sdb2
sudo swapon /dev/sdb2
Swap on File
Flexible method (no partitioning needed).
-
Create empty file: (e.g., 4GB)
sudo fallocate -l 4G /swapfile # Or strict way: sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress -
Secure permissions: (Mandatory)
sudo chmod 600 /swapfile -
Format:
sudo mkswap /swapfile -
Activate:
sudo swapon /swapfile
Persistence (/etc/fstab)
To keep swap after reboot, add to /etc/fstab.
For Partition:
UUID=1234-5678-9abc none swap sw 0 0
For File:
/swapfile none swap sw 0 0
Management
Check Labels / UUID (-L / -U)
Assign a label.
sudo mkswap -L SWAP_PART /dev/sdb2
Verify Status
See active swap devices and usage.
swapon --show
free -h
Remove Swap
sudo swapoff /swapfile
# Then delete the file
sudo rm /swapfile
Notes
- Swappiness: Controlled by
sysctl vm.swappiness. (0-100). Higher means swap more often. - Priority: Can be set in
fstab(pri=10). System uses highest priority swap first.