212

I did not create a swap partition during Ubuntu installation. Later, I freed up some space and made a swap partition. Now after each boot up, I am manually opening gparted to right-click the swap partition to turn on the 'swapon' option.

How can I automatically enable the swap partition at boot?

Also, if I had not created the swap partition, what are my other options?

2
  • 1
    askubuntu.com/questions/299417/…
    – Qasim
    Mar 13, 2014 at 12:04
  • When trying to solve your problem, please note that '/etc/fstab' is not only there for swap memory, but also manages your primary mount point. Thus, edit it carefully. Jan 13, 2023 at 16:15

9 Answers 9

180

You need to edit /etc/fstab and add the new swap partition.

sudo nano /etc/fstab

You need to add a line that looks like

UUID=735b3be3-779c-4d21-a944-b033225f3ab4 none   swap    sw      0       0

and you get the UUID using the command

sudo blkid /dev/sda3

(substitute /dev/sda3 with the appropriate device name; in order to see the appropriate device name, we can use lsblk - as said here).

Related:

10
  • Need Help for /etc/fstan i ma getting output :- bash: /etc/fstab: Permission denied Aug 31, 2014 at 8:20
  • 1
    Use sudo gedit /etc/fstab
    – user323419
    Nov 29, 2014 at 22:37
  • 3
    To find the appropriate device name: sudo fdisk -l (from: askubuntu.com/questions/182446/…) and then look for Type: Linux swap. Aug 17, 2016 at 12:30
  • 1
    sudo blkid /dev/sda4 prints nothing for me (sda4 is newly created partition with code 82h, fdisk says it is "Linux swap / Solaris" partition). Feb 25, 2017 at 21:02
  • 1
    @elvis.dukaj it's perfectly fine to also use the device name. They basically express two different things. One says use the volume with exactly that UUID (something that will change with another mkswap run) and the other says to use primary partition number 3 of disk /dev/sda. Some prefer UUIDs because even if the assignment of device names changes, the UUIDs would remain the same. So that's why the difference matters. But if you are sure that you won't repartition the drive, /dev/sda3 should be equally safe to use. May 24, 2018 at 19:49
137

To create a swap partition after installation, create an empty partition. It should have no holes. You can then format this partition with:

sudo mkswap /dev/sdX

replacing /dev/sdX with your partition. Mount this partition as swap with

sudo swapon -U UUID

where UUID is that of your /dev/sdX as read from this:

blkid /dev/sdX

Bind your new swap in /etc/fstab by adding this line:

UUID=xxx    none    swap    sw      0   0

If you want to use your swap for hibernating then you need to update the UUID in /etc/initramfs-tools/conf.d/resume with this content RESUME=UUID=xxx. Don't forget to $ sudo update-initramfs -u.

To complete things: it is also possible to create a swap file if you do not have a spare partition. This answer gives you an idea of how to create a swap file and enable it on boot.

3
  • As of right now, I have a SSD with two partitions, but I would like to make a third one. If I have a primary ext4 partition that holds the OS and my files, can I use this to peel off 2GB off it into t a new partition? This primary partition has more than enough free space so that shouldn't be an issue.
    – dustin
    Apr 4, 2015 at 22:46
  • 2
    Look at gparted for resizing your partition. Aug 17, 2016 at 12:35
  • command to list all partitions with relevant details: lsblk -e7 -o "NAME,PTTYPE,FSTYPE,SIZE,LABEL,PARTLABEL,PATH,PHY-SEC,VENDOR,UUID" Jan 5, 2023 at 8:19
99

In case you don't want or you're not sure how to create a swap partition, you can create a swap file which will work in the same way as partition. Here are the steps (using terminal):

  1. Create an empty file (1K * 4M = 4 GiB).

    sudo mkdir -v /var/cache/swap
    cd /var/cache/swap
    sudo dd if=/dev/zero of=swapfile bs=1K count=4M
    sudo chmod 600 swapfile
    
  2. Convert newly created file into a swap space file.

    sudo mkswap swapfile
    
  3. Enable file for paging and swapping.

    sudo swapon swapfile
    

    Verify by: swapon -s or top:

    top -bn1 | grep -i swap
    

    Should display line like: KiB Swap: 4194300 total, 4194300 free

    To disable, use sudo swapoff swapfile command.

  4. Add it into fstab file to make it persistent on the next system boot.

    echo "/var/cache/swap/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab
    
  5. Re-test swap file on startup by:

    sudo swapoff swapfile
    sudo swapon -va
    

    Note: Above commands re-checks the syntax of fstab file, otherwise your Linux could not boot up properly.

7
  • 24
    Thank you for the only answer that uses a swapfile and not a swap partition. In this case I could not create a partition. The commands worked great. Feb 4, 2017 at 14:53
  • 4
    For those who need higher size swap space, increase count=4M, to XM, for X GiB swap space. In case if anyone missed it. May 15, 2017 at 8:52
  • 1
    @RaffiKhatchadourian Retesting at the end helps to double check the syntax of fstab file (against any typos), otherwise Linux may not boot up correctly causing major startup issues, especially on remote servers.
    – kenorb
    Jan 2, 2018 at 20:45
  • 2
    Ah I understand now. You need to do that before you reboot. I got thrown off by on start up.
    – khatchad
    Jan 3, 2018 at 3:49
  • 3
    This is great for remote VPS where the disk is actually a virtual device and you don't get control over partitioning. Thanks!
    – ColinM
    Oct 25, 2019 at 21:16
23

There's a graphical way to do this using gparted (if the space you want to assign as swap will come fron an unmounted/unused partition).

Run Gparted with:

sudo gparted

If you don't have it install, you can install it using

sudo apt-get install gparted

Once gparted is running:

  1. Allocate the partition as you would by right-clicking any unallocated block and clicking new
  2. Format the partition as linux-swap
  3. Right-click the partition and clickswapon

There should be a key icon next to your partition name once you're done

7
  • 7
    To make it permanent, you still have to edit fstab file as in the answer by @user4124 Mar 17, 2018 at 4:20
  • 3
    The question already says that they do this. Oct 16, 2018 at 18:31
  • 2
    This doesn't answer the question at all.
    – mook765
    Oct 17, 2018 at 7:22
  • 1
    @mook765, The question is "How do I add swap after system installation?". This perfectly answers that question.
    – salsbury
    Aug 29, 2019 at 14:47
  • @MaduraPradeep Not sure why, but I did not have to edit fstab after following these instructions on Ubuntu 16.04.
    – salsbury
    Aug 29, 2019 at 14:49
4

from linux.com just create swap file as that is more flexible and you can dynamically adjust how many and how large swap storages you have. That also allows you to move swap partition away from your system disk, thus making system faster. Also, if you use several swap spaces, adjust their priority of use to same value, so round-robin is used to write in them, allowing you to get even more speed improvements.

p.s. i would use UUID instead of device name, because it is easily possible to change device order if by accident you leave USB storage inside USB slot and simply removing and plugging back sata cables - you do not need to worry much about what drive is connected where.

1
  • This was the most helpful response, because it does not require re-partitioning the drive. Too bad Ubuntu doesn't create swap by default when you install it on a new machine!
    – Ernie
    Feb 27, 2015 at 17:34
3

You have to have a swap filesystem defined in /etc/fstab. It should contain a line similar to

UUID=67682d1b-a1d8-4377-a3dd-67340c141619 none            swap    sw              0       0

Of course you need to substitute the value of UUID with the identifier of your device.

2
  • how can I get it?
    – user13593
    Apr 5, 2011 at 20:21
  • 3
    You can use the device name instead, like /dev/sda1 (without the UUID). Apr 5, 2011 at 20:30
3

This is a comprehensive Tutorial on how to make a Ram Drive for Ubuntu. Unfortunately.. the screenshots do not show up in this via cut and paste.. Later I will add them, but they are not needed.

The first thing you need to do is create space for your ram drive. I have a dual boot system with only a 32gb hard drive. My Ubuntu is actually installed on an SD card (yes, a real install and not a Live Casper thing). My swap was also on the SD and might get worn out quickly. I looked up how to change the swap and found this article and did not like the answers so I made a tutorial while I made the change.

If you simply wish to increase or decrease your Swap partition, you only need to increase or decrease the partition through your favorite partition manager. Ubuntu already knows where to go and it is size independent. If you want to change the location or make a new Swap, then read on. The first thing you will need to do is Shrink your hard drive to provide space for a swap. If you are shrinking a disk with the Windows system on it, then you'd better use Windows to shrink the disk (It knows its own stuff). If you are on a pure ubuntu, try resizing using a live Ubuntu USB.

Windows Resize Instructions:

  1. Backup your system, and defrag your drive.
  2. Right Click on the start bar.
  3. Select Disk management
  4. Right click ON THE CORRECT DRIVE
  5. Select Shrink.
  6. Type in the correct amount.

If you are in Ubuntu. Make sure you use Ubuntu tools. To finish the allocation, I will use a bootable Live USB of Ubuntu which includes GParted. A Live USB is the best way to use Gparted for any reason, and you should have a USB from your first install or make one to keep handy.

Typing in 2000 was not allowed because there was not enough room to do that even though I had “defragmented” the drive (I do not believe Windows really defragged it). With some experimentation, I was allowed 1000. Then I tried 1000 again and it worked. I should thank my primary school math teacher for that one more than the MS Windows programmers. That left me with 1.95gb which is close enough for my primary school math.

Format the partition

Now I am ready for gparted to format that space as a proper swap drive. If you are in Windows and switching back and forth between Ubuntu and Windows, MAKE SURE YOU HOLD THE SHIFT KEY when clicking "Power" and "Shut down." This is very important, especially when you are messing with the "C" drive particulars in another operating system. If you are dual booting, you should know already that Windows does a fake shut down under normal circumstances. Some people have disabled "Fast Boot". I do not have that choice on my system (Windows 10) and must use the shift key thanks to my friend Google. If you boot with a live USB and you cannot mount the "C" drive (by clicking on it), then you did not fully shut down properly. Reload windows and shut down again using the shift key.

Now you are in Ubuntu Live Mode and read below:

If you are a pure Ubuntu and did not shrink in Windows. You will use the Resize option in gParted. If you already shrank your drive, do not do the resize step. You can type GParted in the Dash bar and get the application quite quickly. Right click on the drive you want to resize.

Now we will format the unallocated space as a partitioned drive:

Before:

I did not know what to do, so I looked at my previous Ram Drive on the SD. It is formatted as Linux Swap. So I formatted my new allocation that I recently shrank as Linux Swap too.
I said OK to the Primary Partition and the warning notice and it worked!

Formatting the partition

After the format and new partition

It is a coincidence that the old swap partition on the sd was called mmblk1p5 and new one is also p5 with mmblk0 in front. Yours could be p6 or p7. Don't worry.

The mmblk0 is the physical disk and p is the partition on that physical disk. And mmblk01 is another physical disk, etc. (That is my SD) Before I did any more work, I opened Windows again to make sure Windows still booted. You do not need to do this step if you are lazy or on a pure ubuntu machine. If it broke Windows, I would likely wipe Windows do a fresh install of Ubuntu on that disk (with a swap too). If I broke my system, I would not need to follow any more steps because I can allocate the swap on the new install. All went well and Windows booted. Now you can see the new partition in the Windows disk manager: (Right click on the start bar to get disk management)

Now attach the Swap to the boot routine

Previous answers to this question actually had swapon/off commands which are not needed and can be complex. All one needs to do is find the right file, and point the swap to the new partition. Again, if you only resized the partition, you do not need to do anything. It is already setup to find the partition. The size gets done automatically.

If you changed the partition or are making a first ever swap, then read below:

Let me tell you that, this is the first time I am doing this. I am not a UNIX geek and I prefer GUI tools. I am learning and crossing my fingers as I make this tutorial. All has gone well so far. At the root of your system is a directory called etc. Inside that directory is a file called fstab (no extension). You will need to edit this file with super user "su" rights. Before we do that, we need the UUID of the new Swap Partition you made with the Live USB. Type sudo su Now you are in Super User mode. You can do anything (including wipe your own existence).

Type blkid and look for the uuid of the new swap partition. I saw mine below and highlighted it:

Pay no attention to PartUID's.

Now, the other people will say type:

sudo gedit /etc/fstab

However, I tried that and it did not find the right file (comments please).

So I just typed gedit and open it the whimpy GUI way (Success!). Since, I was already in Super User mode (sudo su) I have root permission to do ANYTHING in Gedit, including saving the file after I change it. Wonderful! Before you change or corrupt anything, save the fstab as backup called... fstab.bak.

Make the backup by using the whimpy GUI way and choose the familiar “Save As” and add "bak" to the file fstab.bak. Check to see it is there with a .bak extension. Geeks will tell you to use the terminal cp command, but we novices cannot find the file in terminal to get this far in the first place. Just like any word processor, after the “save as” command, your current file is now the fstab.bak. Open the real one you had before, and then close the backup file. Double check to see you are editing the real fstab with no extension. If you edit the backup file, nothing will happen when you reboot, plus your backup copy will not be a real backup of the original.

My original fstab file looks like this:

# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/mmcblk1p6 during installation
UUID=a611601a-6ea8-4e34-9859-42a2470cac29 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/mmcblk0p1 during installation
UUID=00F2-C0CE  /boot/efi       vfat    umask=0077      0       1
# swap was on /dev/mmcblk1p5 during installation
UUID=8fb20159-62e4-41a3-8550-791c7a66c328 none            swap    sw              0       0

The last line (I made red for you), has the original swap info that is used probably on boot up time. From the previous blkid command, I could see my new drive UUID. Copy that phrase by highlighting the text in the terminal and then right clicking and choosing copy. Paste that phrase into another separate editor without su rights as a scratch pad (you can use Libre Office, and geeks can use nano). This step helps you get the right text easily without the quotes so you can paste easily into the fstab file. You want to change this file as little as possible.

New UUID
UUID="709ea197-e6fb-428b-9c1f-4b258452b10c"

So, my new UUID is listed in red above. All I need to do is change the uuid for the swap. If you have no swap drive, then copy my line in the above fstab file and then add the proper uuid from the previous blkid command. (choose the right uuid please!)
If this is your first Swap line, make sure you includes the complete line with the extra stuff

none            swap    sw              0       0

Do not worry about the exact spacing so much.

My new file looks like this: Notice I added a comment above my change too The # character means it is a comment.

# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/mmcblk1p6 during installation
UUID=a611601a-6ea8-4e34-9859-42a2470cac29 /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/mmcblk0p1 during installation
UUID=00F2-C0CE  /boot/efi       vfat    umask=0077      0       1
# swap was on /dev/mmcblk1p5 during installation  NOW changed to mmcblk0p5
UUID= 709ea197-e6fb-428b-9c1f-4b258452b10c  none            swap    sw              0       0

Do not paste the quotes. Do not have spaces after the = sign.

Save your file.

Open it again, just to be sure your changes saved. Close the gedit and terminal with dangerous su rights that geeks will scold you for doing (because it is easy work with... and easy to destroy things too).

REBOOT and and cross your fingers!

I rebooted and then I checked to see if my swap was working by looking at system performance app. I still had a Swap drive! But was it the new one or the old one? I could not verify my new drive was actually loaded because the new one is the same size as the old drive. Therefore, I typed: swapon (DO NOT TYPE ANYTHING MORE THAN SWAPON and it will only list the swap for you: safe). Now I see my new drive on mmblk0p5 which matches the UUID work I did on fstab. My slim 32gb main drive took effect:


This concludes this tutorial from a novice user who has never done this before. Half of the reason I made this tutorial was so the Geeks who help us (and thank you) can see how to help novice users. I suspected the previous answers were misleading and decided to make a tutorial as I did my work... By guessing from the other answers which were useful, I concluded that all I needed to do was edit the fstab flle and reboot. All worked well and I still have windows 10 and have not wiped my system yet. If anyone knows how to share a Windows pagefile.sys as a Linux swap file, I would be interested since 2 gb is taken for that in Windows and hd space is very pricy on my 32 GB machine.

2

(replace the "x" in sdax with swap partition number eg: sda5)

replace "xxx" with UUID number eg: 67682d1b-a1d8-4377-a3dd-67340c141619)


su (give password to get root permission)

blkid /dev/sdax (get UUID) mkswap /dev/sdax (format swap partition) swapon -U xxx

nano /etc/fstab (edit fstab) UUID=xxx none swap sw 0 0 (enter and save this text to make swap permanant) (then close fsantab)


nano /etc/initramfs-tools/conf.d/resume (create "resume" file and save this text to use hibernate/resume) RESUME=UUID=xxx (ctrl+x to close nano)->(y to save)

restart machine

login and now you can test hibernate / resume

0

If you installed new empty disk then need to create swap partition on it.

  1. Show partitions:

    $ sudo fdisk -l

    Disk /dev/sdb: 4.1 GiB, 4420796416 bytes, 8634368 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes

  2. Create swap partition:

    $ sudo fdisk /dev/sdb

    Welcome to fdisk (util-linux 2.31.1). Changes will remain in memory only, until you decide to write them. Be careful before using the write command.

    Device does not contain a recognized partition table. Created a new DOS disklabel with disk identifier 0xbf65f113.

    Command (m for help): m

    Help:

    DOS (MBR) a toggle a bootable flag b edit nested BSD disklabel c toggle the dos compatibility flag

    Generic d delete a partition F list free unpartitioned space l list known partition types n add a new partition p print the partition table t change a partition type v verify the partition table i print information about a partition

    Misc m print this menu u change display/entry units x extra functionality (experts only)

    Script I load disk layout from sfdisk script file O dump disk layout to sfdisk script file

    Save & Exit w write table to disk and exit q quit without saving changes

    Create a new label g create a new empty GPT partition table G create a new empty SGI (IRIX) partition table o create a new empty DOS partition table s create a new empty Sun partition table

    Command (m for help): n Partition type p primary (0 primary, 0 extended, 4 free) e extended (container for logical partitions) Select (default p): p Partition number (1-4, default 1): First sector (2048-8634367, default 2048): Last sector, +sectors or +size{K,M,G,T,P} (2048-8634367, default 8634367):

    Created a new partition 1 of type 'Linux' and of size 4.1 GiB.

    Command (m for help): t Selected partition 1 Hex code (type L to list all codes): L

    0 Empty 24 NEC DOS 81 Minix / old Lin bf Solaris
    1 FAT12 27 Hidden NTFS Win 82 Linux swap / So c1 DRDOS/sec (FAT- 2 XENIX root 39 Plan 9 83 Linux c4 DRDOS/sec (FAT- 3 XENIX usr 3c PartitionMagic 84 OS/2 hidden or c6 DRDOS/sec (FAT- 4 FAT16 <32M 40 Venix 80286 85 Linux extended c7 Syrinx
    5 Extended 41 PPC PReP Boot 86 NTFS volume set da Non-FS data
    6 FAT16 42 SFS 87 NTFS volume set db CP/M / CTOS / . 7 HPFS/NTFS/exFAT 4d QNX4.x 88 Linux plaintext de Dell Utility
    8 AIX 4e QNX4.x 2nd part 8e Linux LVM df BootIt
    9 AIX bootable 4f QNX4.x 3rd part 93 Amoeba e1 DOS access
    a OS/2 Boot Manag 50 OnTrack DM 94 Amoeba BBT e3 DOS R/O
    b W95 FAT32 51 OnTrack DM6 Aux 9f BSD/OS e4 SpeedStor
    c W95 FAT32 (LBA) 52 CP/M a0 IBM Thinkpad hi ea Rufus alignment e W95 FAT16 (LBA) 53 OnTrack DM6 Aux a5 FreeBSD eb BeOS fs
    f W95 Ext'd (LBA) 54 OnTrackDM6 a6 OpenBSD ee GPT
    10 OPUS 55 EZ-Drive a7 NeXTSTEP ef EFI (FAT-12/16/ 11 Hidden FAT12 56 Golden Bow a8 Darwin UFS f0 Linux/PA-RISC b 12 Compaq diagnost 5c Priam Edisk a9 NetBSD f1 SpeedStor
    14 Hidden FAT16 <3 61 SpeedStor ab Darwin boot f4 SpeedStor
    16 Hidden FAT16 63 GNU HURD or Sys af HFS / HFS+ f2 DOS secondary
    17 Hidden HPFS/NTF 64 Novell Netware b7 BSDI fs fb VMware VMFS
    18 AST SmartSleep 65 Novell Netware b8 BSDI swap fc VMware VMKCORE 1b Hidden W95 FAT3 70 DiskSecure Mult bb Boot Wizard hid fd Linux raid auto 1c Hidden W95 FAT3 75 PC/IX bc Acronis FAT32 L fe LANstep
    1e Hidden W95 FAT1 80 Old Minix be Solaris boot ff BBT
    Hex code (type L to list all codes): 82 Changed type of partition 'Linux' to 'Linux swap / Solaris'.

    Command (m for help): m

    Help:

    DOS (MBR) a toggle a bootable flag b edit nested BSD disklabel c toggle the dos compatibility flag

    Generic d delete a partition F list free unpartitioned space l list known partition types n add a new partition p print the partition table t change a partition type v verify the partition table i print information about a partition

    Misc m print this menu u change display/entry units x extra functionality (experts only)

    Script I load disk layout from sfdisk script file O dump disk layout to sfdisk script file

    Save & Exit w write table to disk and exit q quit without saving changes

    Create a new label g create a new empty GPT partition table G create a new empty SGI (IRIX) partition table o create a new empty DOS partition table s create a new empty Sun partition table

    Command (m for help): w The partition table has been altered. Calling ioctl() to re-read partition table. Syncing disks.

  3. Make partition swap:

    $ sudo mkswap /dev/sdb1 Setting up swapspace version 1, size = 4.1 GiB (4419743744 bytes) no label, UUID=e2c53e87-c32c-4230-8405-25b471af6524

  4. Use turn on swap on created partition:

    sudo swapon -U e2c53e87-c32c-4230-8405-25b471af6524

  5. Make swap permanently:

    sudo nano /etc/fstab

Add line below and save file.

UUID=e2c53e87-c32c-4230-8405-25b471af6524 none  swap    0
  1. Check swap

    sudo free -m total used free shared buff/cache available Mem: 1993 203 1271 6 518 1635 Swap: 4214 0 4214

Done.

You must log in to answer this question.