+
+
js
@
+
+
+
mint
+
+
+
+
+
+
+
fauna
azure
+
+
express
rollup
windows
ts
+
c
&
&
+
swc
+
+
+
+
gh
@
nuxt
+
+
+
+
qdrant
+
html
solid
+
+
+
android
+
@
kali
svelte
https
+
bundler
+
goland
+
+
junit
strapi
...
+
c
+
&
+
elementary
puppet
debian
hugging
elm
+
+
+
+
zig
+
ios
+
+
+
termux
actix
+
+
cobol
Back to Blog
What is the best command for creating a swap file on Linux?
Linux

What is the best command for creating a swap file on Linux?

Published Nov 7, 2023

This tutorial explains which is the best command for creating a swap file on Linux.

1 min read
0 views
Table of Contents

This tutorial explains which is the best command for creating a swap file on Linux.

Fallocate VS dd Commands in Linux

fallocate is much faster, but may create files with holes. This means the space is not contiguous, which is problematic for swap files. fallocate creates a C-style linked-list of memory, whereas dd creates a contiguous block of memory.

The swapon and mkswap manpages recommend against using fallocate, specifically noting:

You should not use swapon on a file with holes.

Note that a swap file must not contain any holes.

It is recommended to use dd with /dev/zero to create swap files, ensuring a contiguous memory block.

Creating a Swap File with dd

Here’s the proper way to create a swap file using dd:

# Create a 4GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress

# Set correct permissions
sudo chmod 600 /swapfile

# Set up the swap area
sudo mkswap /swapfile

# Enable the swap file
sudo swapon /swapfile

# Verify it's working
sudo swapon --show

Making Swap Permanent

To make the swap file permanent, add it to /etc/fstab:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Why Not Fallocate?

While fallocate is faster:

# This is NOT recommended for swap files
sudo fallocate -l 4G /swapfile

It may create sparse files (files with holes), which are incompatible with swap functionality. Always use dd for swap file creation to ensure a contiguous memory block.