Add a SWAP File to Linux

   Under some customized Linux OS, they may remove the swap file, if you want to add a swap file while login to the system, is that possible?
   Obviously it is!

  1. Login as a root user. If you want to change some system settings, you must be a root user.
  2. Create a storage file. The following command creates a 2 GB file.
[[email protected] ~]# dd if=/dev/zero of=/swapfile bs=1024 count=2097152
2097152+0 records in
2097152+0 records out
2147483648 bytes (2 GB) copied, 12.23347 s, 166 MB/s


i. if=/dev/zero : Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile.
ii. of=/swapfile : Read from /dev/zero write storage file to /swapfile.
iii. bs=1024 : Read and write 1024 BYTES bytes at a time.
iv. count=2097152 : Copy only 2097152 BLOCKS input blocks.
3. Secure the swap file. Setup correct file permission for security reasons, enter:

[[email protected] ~]# chown root:root /swapfile
[[email protected] ~]# chmod 0600 /swapfile
  1. Set up a Linux swap area. Type the following command to set up a Linux swap area in a file:
[[email protected] ~]# mkswap /swapfile
  1. Enabling the swap file. Finally, activate /swapfile swap space immediately, enter:
[[email protected] ~]# swapon /swapfile

Now you can check if the swap works by following command:

[[email protected] ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            986          96          75           0         814         695
Swap:          2047           0        2047
  1. Update /etc/fstab file. To activate /swapfile after Linux system reboot, add entry to /etc/fstab file. Open this file using a text editor such as vim:
[[email protected] ~]# vim /etc/fstab

Append the following line:

  /swapfile1 none swap sw 0 0

Save and close the file. Next time Linux comes up after reboot, it enables the new swap file for you automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *