How to use the command swapon (with examples)
- Linux
- December 25, 2023
The swapon
command is used to enable devices and files for swapping in Linux. Swapping is a technique used by the operating system to move inactive or less frequently used memory pages from RAM to a disk or a file, thereby freeing up memory for other processes. This command allows you to manage and enable swap areas, either by specifying a file or by using the swap partition label.
Use case 1: Show swap information
Code:
swapon
Motivation: This command is useful when you want to display the current swap configuration, including the active swap areas and their sizes.
Explanation: When executed without any arguments, swapon
displays the current swap configuration. It provides information about the active swap areas, such as file or device path and the size of each swap area.
Example output:
NAME TYPE SIZE USED PRIO
/dev/sda2 partition 2G 0B -2
In this example output, the current swap configuration includes a swap partition /dev/sda2
with a size of 2GB.
Use case 2: Enable a given swap area
Code:
swapon path/to/file
Motivation: This command is used to enable a specific swap area, which can be a regular file or a swap partition. Enabling swap areas allows the operating system to use them for memory swapping.
Explanation: By providing the path to a file or swap partition as an argument to swapon
, you can enable that particular swap area. The system then starts to make use of the specified file or partition for swapping.
Example output: No output is displayed after enabling a swap area.
Use case 3: Enable all swap areas specified in /etc/fstab
Code:
swapon --all
Motivation: This command is used to enable all swap areas specified in the /etc/fstab
file, excluding those with the noauto
option. It is a convenient way to enable multiple swap areas at once.
Explanation: The --all
option instructs swapon
to enable all swap areas specified in the /etc/fstab
file. It skips any swap areas with the noauto
option, which is commonly used to prevent automatic enabling of certain swap areas during system startup.
Example output: No output is displayed after enabling the swap areas.
Use case 4: Enable a swap partition by its label
Code:
swapon -L label
Motivation: This command is helpful when you want to enable a swap partition specifically by its label. It simplifies the process of enabling a swap partition instead of specifying the partition path.
Explanation: The -L
option allows you to enable a swap partition by its label. By providing the label of the swap partition as an argument, swapon
identifies and enables that partition for swapping.
Example output: No output is displayed after enabling the swap partition.