Skip to content

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

  1. Create partition (Type 82 - Linux Swap) via fdisk or gdisk.
  2. Format as swap:

sudo mkswap /dev/sdb2
3. Enable:

sudo swapon /dev/sdb2

Swap on File

Flexible method (no partitioning needed).

  1. 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
    

  2. Secure permissions: (Mandatory)

    sudo chmod 600 /swapfile
    

  3. Format:

    sudo mkswap /swapfile
    

  4. 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
Or:
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.