267 words
1 minutes
π§ How to Create a Linux Swap File

Create, activate, and manage swap space on a Linux server using a simple, interactive Bash script.
π οΈ Option 1: Quick Setup with create-swap.sh
π Save the Script
-
Create the script file:
nano create-swap.sh
-
Paste this script inside:
#!/bin/bash # Prompt the user for swap size read -p "Enter swap size in MB (e.g., 1024 for 1GB): " SWAP_SIZE_MB # Validate input if ! [[ "$SWAP_SIZE_MB" =~ ^[0-9]+$ ]]; then echo "β Error: Please enter a valid numeric value." exit 1 fi SWAP_FILE="/swapfile" echo "π οΈ Creating a ${SWAP_SIZE_MB}MB swap file at ${SWAP_FILE}..." # Create the swap file if ! sudo fallocate -l ${SWAP_SIZE_MB}M ${SWAP_FILE}; then echo "β οΈ fallocate failed, falling back to dd..." sudo dd if=/dev/zero of=${SWAP_FILE} bs=1M count=${SWAP_SIZE_MB} status=progress fi # Set the correct permissions sudo chmod 600 ${SWAP_FILE} # Format the file as swap sudo mkswap ${SWAP_FILE} # Enable the swap file sudo swapon ${SWAP_FILE} # Make the swap persistent if ! grep -q "${SWAP_FILE}" /etc/fstab; then echo "${SWAP_FILE} none swap sw 0 0" | sudo tee -a /etc/fstab > /dev/null fi echo "β Swap setup completed!" swapon --show free -h
-
Run the script:
chmod +x create-swap.sh && ./create-swap.sh
π οΈ Option 2: Manual Swap File Creation
-
Create a 1GB swap file (change the size as needed):
sudo fallocate -l 1G /swapfile
OR use
dd
as a fallback (only if the first command is not working):sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress
-
Secure the file:
sudo chmod 600 /swapfile
-
Set it up as swap:
sudo mkswap /swapfile
-
Enable the swap:
sudo swapon /swapfile
-
Make it permanent:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
-
Confirm itβs active:
swapon --show free -h
WARNINGTo Remove the Swap File:
sudo swapoff /swapfile && rm /swapfile && sed -i '/\/swapfile/d' /etc/fstab
π§ How to Create a Linux Swap File
https://www.itsnooblk.com/posts/create-swap/