We know what is Swap memory in Linux and why it is so important to have one. Swap is your RAM’s best buddy and helps him run the OS smoothly. If you’re a newbie and just went created the ‘/’ or forgot to create a swap partition, don’t worry, in this post we’ll see how to create a Swap partition in Linux, if you don’t have one.
We already have a Linux Ubuntu OS which has no Swap memory. We’ll create a swap partition using fdisk
command. So let’s see how to add a swap partition.
sudo fdisk -l
As you can see, we don’t have a swap partition. Take a note of your Disk (/dev/sda in this case).
Press ‘n‘ for New Partition.sudo fdisk /dev/sda
‘P’ to select type of partition as ‘Primary‘. If you have more than 4 partitions, you’ll have to type ‘e‘ to set the type as extended.
Since I have only one partition, I will set partition number as default i.e. the next one: 2.
Press ‘Enter‘ to select default sector.
Enter the size of Swap partition as ‘+sizeOfPartition‘ when it asks you for last sector.- Each partition type in Linux has a hex code to recognize it. When we create any partition it gives it the default hex code of 83 (Linux file system).
We need to make it a ‘Swap partition’, so we need to change the code of the partition.
We can do this by using ‘t‘ to toggle type of the partition we want to change.
Select partition of which you want to change the id. Since we just created Partition 2 and want to make it swap memory, we’ll enter 2.
It’ll then ask you which file system do you want to change it to. You can type ‘L’ to see the list of codes.
- The hex code of Linux Swap is 82. So enter 82 and then print the partition table to check.
partprobe
Press w to save and quit. Allchangeswill be saved, but you can’t see it immediately. It’ll show in the next type system starts. If you want to see it instantly run partprobe.sudo mkswap /dev/sda2
sudo swapon -U UUID
blkid /dev/sda2 (to get UUID)
Format the new partition with ‘sudo mkswap /dev/sdaX‘ where X is your partition id.
Mount the new parition as swap using ‘swapon’ command.
If you don’t know UUID, use ‘blkid’ command to get UUID of your partition.sudo vim /etc/fstab
UUID=xxx none swap sw 0 0
Open fstab and add the new entry to make it permanent. Save and exit.swapon -s
Verify the swap partition