Advertisements

How to Create a Swap File in Linux When Repartitioning Isn’t an Option

  • Post last modified:October 19, 2023
  • Post category:Linux
  • Post comments:2 Comments
  • Reading time:5 mins read

Adding swap space to your system is necessary for efficient memory management, but repartitioning your existing disk is not possible. In such cases, Linux provides a solution – creating swap space inside a file. In this post, I will show you how to create a swap space inside a file.

Table of Contents:

Step 1: Create the Swap File

Advertisements

Open a terminal window and enter the following command to create a swap file of 1GB (1,048,576 KB) you can change the size if you want:

dd if=/dev/zero of=/swapfile1 bs=1024 count=1048576

Step 2: Set Permissions

Set the correct permissions for the swap file. Enter the following commands to change the ownership to the root user and set the file permissions to read and write for the root user only:

chown root:root /swapfile1
chmod 0600 /swapfile1

Step 3: Create Swap Space

Create swap space on the swap file by running the following command:

mkswap /swapfile1

Step 4: Activate the Swap File

Activate the swap file:

swapon /swapfile1

This command enables the swap file and makes it available for use as swap space in the system.

Step 5: Make Swap Permanent

To make the swap file permanent and have it automatically activated on system boot, we need to add an entry to the /etc/fstab file. Run the following command:

echo "/swapfile1 none swap sw 0 0" >> /etc/fstab

Step 6: Verify Swap Space

You can verify that the swap file is active and being used as swap space by running the following command:

free -m

Advertisements

This command will show the system’s memory usage, including the swap space. You should see the swap file listed as part of the output.

Conclusion

Creating swap space inside a file is a good idea when repartitioning your existing disk is not possible. By following the step-by-step process outlined in this post, you can easily create swap space inside a file.

This Post Has 2 Comments

  1. Entity

    hey thanks for the post and how can add 8gb swap file ?

    1. Udara Kalana

      bs=1024: Specifies the block size as 1024 bytes.
      count=8388608: Calculates the number of blocks needed to create an 8 GB file (8 * 1024^3 / 1024) and sets it as the count value.

      dd if=/dev/zero of=/swapfile1 bs=1024 count=8388608 8GB file

Leave a Reply