Skip to content

Instantly share code, notes, and snippets.

@darkerego
Created August 9, 2024 03:34
Show Gist options
  • Save darkerego/f6ffe2a72dd44d3d883040667b0d9104 to your computer and use it in GitHub Desktop.
Save darkerego/f6ffe2a72dd44d3d883040667b0d9104 to your computer and use it in GitHub Desktop.
mkswap.sh
#!/bin/bash
# Get the total memory in kilobytes
TOTAL_MEM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}')
# Calculate half of the total memory
HALF_MEM_KB=$((TOTAL_MEM_KB / 2))
# Convert kilobytes to megabytes (MB)
HALF_MEM_MB=$((HALF_MEM_KB / 1024))
# Define the swap file location
SWAPFILE=/swapfile
# Create a swap file with the calculated size
sudo fallocate -l "${HALF_MEM_MB}M" $SWAPFILE
# Set the correct permissions for the swap file
sudo chmod 600 $SWAPFILE
# Set up the swap area on the file
sudo mkswap $SWAPFILE
# Enable the swap file for usage
sudo swapon $SWAPFILE
# Add the swap file entry to /etc/fstab for persistent swap file usage
echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
# Display the new swap status
sudo swapon --show
# Display the current memory and swap usage
free -h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment