Creating a Linux swap file is a small administrative task with consequences beyond the command that creates it. The file must be suitable for the filesystem, protected appropriately, activated successfully, and integrated with the machine's startup policy. A command copied without those checks can leave you with an unused file or a configuration problem at the next reboot.
This guide uses an ordinary local ext4 filesystem as a deliberately narrow example. It is not a universal recipe for Btrfs, network filesystems, encrypted-resume configurations, or managed production fleets. Read each checkpoint before proceeding, and stop after any error rather than continuing through the remaining commands.
Decide whether a new swap file is the right change
Start with the symptom you are trying to address. A temporary memory-demand peak is different from a workload that continually exceeds the machine's useful RAM capacity. Adding backing space may help with the former without making the latter responsive.
Check whether swap already exists. Some installations use a partition, a file, a compressed zram device, or a combination. Creating another file without understanding the current arrangement can complicate priorities and monitoring. Use the Linux mem swap overview to identify the existing design first.
On a managed system, inspect the configuration-management policy before making local changes. A manual edit may be reverted, duplicated, or inconsistent with other machines. Coordinate a maintenance window for production changes and keep an administrative session or recovery console available.
Perform read-only checks first
The following commands inspect configuration; they do not create or activate swap:
swapon --show
free -h
findmnt -no FSTYPE /
df -h /
Review the output instead of treating these as ceremonial steps. Confirm the filesystem containing the proposed file, the existing swap entries, and sufficient free storage for both the file and normal system work. If the proposed location is on a different mount from /, inspect that mount instead.
Check whether /swapfile already exists before using the example path. An existing file may already be part of a configured memory policy, even if it is not currently active. Do not overwrite it or repurpose an unfamiliar path. Choose a planned new location only after verifying its purpose and filesystem.
Understand filesystem restrictions
A swap file is not an ordinary document that can be placed on any filesystem with free space. Its backing blocks must meet the kernel and filesystem requirements. Sparse files and certain copy-on-write arrangements require particular care.
The util-linux swapon manual describes restrictions involving holes, copy-on-write files, and filesystem-specific support. It is the technical reference for the activation step in this guide. Btrfs users should follow a Btrfs-specific procedure rather than adapting the ext4 example by guesswork.
Likewise, do not substitute a network mount, an unfamiliar virtual filesystem, or removable storage merely because it has room. Storage availability and startup ordering matter. If the environment does not match the stated scope, pause and use the documentation for that environment.
Create a deliberately bounded example file
The example below allocates 2 GiB. That is a demonstration size, not a recommendation for your machine. Select capacity using the workload-based swap sizing guide before creating the real file. Make sure the destination has adequate space remaining afterward.
Run each command separately, inspecting its result before proceeding. The exclusive-create flag on the first command is important: it is intended to fail if the destination already exists rather than overwrite an existing file.
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 oflag=excl status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
These commands write data and change system configuration. Use the exact new file path you have checked. Never replace it with a disk device or partition that contains data. If creation is interrupted or any step fails, investigate the specific error before running later commands.
Restricting permissions matters because swap can contain application data. However, permissions are not a replacement for an appropriate disk-encryption policy. Decide how sensitive memory contents should be protected when the machine is powered off, lost, or accessed through another operating system.
Check the path and permissions explicitly
Inspect ls -l /swapfile after creation to confirm the intended file and restrictive permissions. Use findmnt -T /swapfile to verify the mount containing that exact path rather than relying on an assumption about the root filesystem. Record the file size and available storage after allocation. If the file unexpectedly resides on another mount, stop and reassess its suitability before activation. These checks are especially useful on machines with separate data volumes or a nonstandard directory layout, where a familiar pathname can conceal a different storage arrangement.
Verify activation before making it persistent
After successful activation, inspect the current state again:
swapon --show
free -h
The new entry should appear with the expected path and capacity. It need not immediately show meaningful usage. Activation and current occupancy are different things; there is no reason to manufacture a memory crisis just to make a usage counter increase.
If the entry is missing, do not jump straight to editing startup files. Resolve the activation failure first. Review the command's error text, filesystem suitability, permissions, and available storage. A persistence entry cannot repair a file that the running system cannot activate.
Also confirm that the rest of the workload still behaves normally. Retain the before-and-after observations. Successful command execution is necessary, but it is not the same as demonstrating that the original performance or reliability problem has improved.
Make persistence a separate, reversible step
On systems that use /etc/fstab for this purpose, an administrator may add an entry for the verified file. Back up the existing configuration, check for duplicate entries, and use the distribution's established editing and validation procedure. Do not blindly append the same line every time a command is rerun.
A conventional entry for this exact example is:
/swapfile none swap sw 0 0
Other arrangements may be managed by systemd units, distribution tooling, or configuration management. Use one coherent ownership model. Document which mechanism creates and activates the file so a future administrator does not unintentionally create a conflicting configuration.
Reboot verification belongs in a planned maintenance window, not in the middle of unsaved work. After reboot, repeat the read-only checks and confirm that required applications start correctly. Keep the previous configuration available in case the new startup behavior needs to be reversed.
Do not confuse ordinary swap with hibernation setup
An active swap file does not establish that suspend-to-disk is configured. Resume handling may need a specific device, file offset, boot parameter, encryption arrangement, and sufficient capacity for the relevant system. Those requirements depend on the distribution and configuration.
For a laptop that relies on hibernation, treat resume support as its own project. Verify the documented procedure and test it with saved work. Do not assume that copying a desktop swap-file command will preserve an existing hibernation path or create a new one automatically.
This separation also helps troubleshooting. “Swap is active” and “the machine resumes reliably” are different acceptance criteria. Record and test both when both features are required.
Plan removal before it becomes an emergency
Removing swap is not simply deleting its backing file. An active area must be handled through the operating system, and displaced memory may need somewhere else to go. A heavily pressured machine is a poor place to experiment with broad swap-disable commands.
For a planned removal, reduce demand, save work, inspect usage and available memory, and follow the distribution's controlled deactivation procedure for the specific area. Remove or update the matching persistence configuration only as part of that documented change. Delete the file only after verifying that it is inactive and no longer needed.
Keep a brief change record with the path, capacity, filesystem, activation method, persistence method, and reason for the configuration. That small record is often more valuable than another tuning parameter because it makes future maintenance predictable.
Conclusion: creation is only one checkpoint
A reliable Linux swap-file setup includes suitability checks, careful creation, restrictive permissions, verified activation, deliberate persistence, and a recovery plan. None of those steps substitutes for measuring whether the workload benefits.
Once the configuration is stable, observe normal and peak usage before considering policy changes. Our swappiness testing guide explains how to evaluate a separate tuning question without treating it as part of the basic file-creation procedure.



