Interested in creating and enabling swap in Linux? Either way, this post can be beneficial for future reference!
Before I get into the whole spiel on commands you need to run… Let me simply point out that you can skip down a bit and run my automated script that will interactively setup swap for you!!!
Anyways, let’s begin! First, we will need to create our swapfile… You should create your swapfile somewhere on your system with reliable storage… In this post, I will be creating my swapfile in the following directory:
sudo touch /mnt/swapfile
Next, we will need to allocate the amount of swap for our file that we want… In this example, I use 2GB (the equivalent of 1024 x 2048 MB) of swap, but you can replace this number with anything you want!!! Remember to change the location of my swapfile with yours also… Anyways, to allocate this space, simply run:
sudo dd if=/dev/zero of=/mnt/swapfile bs=1024 count=2097152
What this does is it creates a file with read and write speeds of 1024 bytes per second (basically what the bs or block-size means) and the size of the file from the count argument… Now, we will want to make sure our swap file is secure, meaning to prevent unauthorized parties from accessing our swapped data… To “secure” our swapfile, run:
sudo chmod 600 /mnt/swapfile
As we finish setting our swapfile up, we will need to actually set up a Linux swap area… We can do so by running:
sudo mkswap /mnt/swapfile
Finally, we can enable this newly created swapfile with a simple command… Without further ado, run:
sudo swapon /mnt/swapfile
And congratulations!!! You have successfully enabled swap on Linux! Oh and before I forget… If you want to automatically have swap enabled every time you are booted into your machine, you will have to run:
echo "/mnt/swapfile swap swap defaults 0 0" >> /etc/fstab
Now you will have swap automatically enabled everytime you reboot!
Are you too lazy to run a couple of commands above? Well if you’re, I recommend using one of my newly created scripts that will automatically create and set up a “swapfile” for you interactively…
To get started, you will need to clone my scripts repository! you can do so by running:
git clone [email protected]:NerdOfCode/Scripts.git
Finally, you will need to run my script by simply running:
And voila!!! Most likely, by this time in the post you have successfully created and enabled a “swapfile” in Linux! I hope this was a nice and easy read for all you Linux fans out there!!!