How to add Linux Swap file if you don’t have Swap Partition

Picture this, you’re running a lot of process that consumes a lot of memory that even your 2GB RAM is running out faster than you can blink your eye. Suddenly your machine slows down to a crawl, then it begin to hang, and all you can do is pray that you wont lose any valuable data should one of the process be killed.

You realised now that you should have allocate more space to that dwarfish 100MB swap partition, seems like it is too late as you need to repartition your hard disk to resize the swap partition to avoid this problem when running memory intensive program. All is lost…

Enter the Swap file…

Actually you can substitute a swap partition with swap files if you need more swap. What you need to do is create an empty file with the size of the swap that you preferred (for example 500MB) and add this information to your fstab.

How to add more Linux Swap with Swap File

Assuming you want to put it in “/”, Create an empty 500MB file
$ sudo dd if=/dev/zero of=/swap.img bs=1024k count=512

Format it as a swap file
$ sudo mkswap /swap.img

Add it to your running Linux system
$ sudo swapon /swap.img

Optionally you can add /swap.img to fstab for automatic swap activation.

$ sudo gedit /etc/fstab

Add this line at the end of the file
/swap.img none swap sw 0 0

Run “free -m” command to verify that you’ve added the newly created swap to your Linux based operating system.

Hope that helps!

[tags]linux,ubuntu,debian,opensource,open source,fstab,swap[/tags]

13 Replies to “How to add Linux Swap file if you don’t have Swap Partition”

  1. Great article!

    Only a question. What if I want to make a partition of a different size? For example, a 250 MB one. What should I change in the following line?
    $ sudo dd if=/dev/zero of=/swap.img bs=1024k count=512

    Should I change bs=1024k into bs=512k and count=512 into count=256 OR only count=512 into count=256 ?

    Thanks in advance.

  2. To Hoang:

    I don’t know if you’ve found the answer to this already or not, but yes, you can put the swap file anywhere you want it. You can also name it whatever you like, I’m pretty sure. As long as your running Linux system knows where to find it, you should be good.

  3. Thank you, this is really helpful!
    I just wonder if I can put the swap file on other device (like /dev/sda1) instead of root folder /

  4. Coooool tip to avoid resizing of the linux
    partitions without re-partitioning / other

    Karthik Balaguru

  5. thanks for the tip . lame me for using partition magic to resize or create my swap space. never knew this tips before . thehehe

Comments are closed.