Date
Nov. 21st, 2024
 
2024年 10月 21日

Post: How to increase swap space on your Raspberry Pi

How to increase swap space on your Raspberry Pi

Published 17:04 Apr 12, 2024.

Created by @ezra. Categorized in #UNIX/Linux, and tagged as #UNIX/Linux.

Source format: Markdown

Table of Content

To increase swap space on your Raspberry Pi, you can follow these steps:

Check Current Swap Space

Before making any changes, it's a good idea to check how much swap space is currently available on your Raspberry Pi. You can do this by running the following command in the terminal:

free -h

This command will display information about your system's memory usage, including swap space.

Create a Swap File

If your Raspberry Pi doesn't already have a swap file, you can create one. First, determine the size of the swap file you want to create. For example, to create a 1GB swap file, you can use the following command:

sudo fallocate -l 1G /swapfile

Replace 1G with the desired size of the swap file. Keep in mind that the size of the swap file should not exceed the available disk space on your Raspberry Pi's SD card.

Set Permissions

After creating the swap file, you need to set the correct permissions:

sudo chmod 600 /swapfile

Set Up Swap Space

Next, set up the swap space using the following command:

sudo mkswap /swapfile

Activate Swap Space

Once the swap file is created and set up, you can activate it using the following command:

sudo swapon /swapfile

Make Swap Permanent

To ensure that the swap space is activated automatically after each reboot, you need to add an entry for the swap file in the /etc/fstab file. Open the file using a text editor such as nano:

sudo nano /etc/fstab

Add the following line to the end of the file:

/swapfile none swap sw 0 0

Save the changes and exit the text editor.

Verify Swap Space

Finally, verify that the swap space is active by running the free -h command again. You should see the newly added swap space listed in the output.

By following these steps, you can increase the swap space on your Raspberry Pi, which should help alleviate memory constraints during resource-intensive tasks like compiling software packages.

Example Script

#!/bin/bash
SPACE_SIZE="$(whiptail --title "Size" --inputbox "Size of swapfile swap space" 15 60 "8G" 3>&1 1>&2 2>&3)"
exitstatus=$?
if [ $exitstatus = 0 ]; then
    free -h
    echo "========> Starting ..."
    sudo fallocate -l "$SPACE_SIZE" /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    sudo grep -qxF "/swapfile none swap sw 0 0" /etc/fstab || echo "/swapfile none swap sw 0 0" | sudo tee --append /etc/fstab
    echo "========> Done ..."
    free -h
fi
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询