Created
December 1, 2025 11:25
-
-
Save ImBIOS/4d01c9bd246563aec65e1e3429d76587 to your computer and use it in GitHub Desktop.
Ubuntu Swap Configuration Script. Sets swap to recommended amount based on system RAM.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Ubuntu Swap Configuration Script | |
| # Sets swap to recommended amount based on system RAM | |
| set -e | |
| # Check if running as root | |
| if [[ $EUID -ne 0 ]]; then | |
| echo "This script must be run as root (use sudo)" | |
| exit 1 | |
| fi | |
| # Get total RAM in GB | |
| TOTAL_RAM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}') | |
| TOTAL_RAM_GB=$((TOTAL_RAM_KB / 1024 / 1024)) | |
| echo "System RAM: ${TOTAL_RAM_GB}GB" | |
| # Determine recommended swap size based on Ubuntu/Red Hat recommendations | |
| if [ $TOTAL_RAM_GB -le 2 ]; then | |
| SWAP_SIZE="${TOTAL_RAM_GB}G" | |
| echo "Recommended swap: ${SWAP_SIZE} (equal to RAM for systems ≤2GB)" | |
| elif [ $TOTAL_RAM_GB -le 8 ]; then | |
| SWAP_SIZE="4G" | |
| echo "Recommended swap: ${SWAP_SIZE} (minimum 4GB for systems 2-8GB RAM)" | |
| elif [ $TOTAL_RAM_GB -le 64 ]; then | |
| SWAP_SIZE="8G" | |
| echo "Recommended swap: ${SWAP_SIZE} (8GB for systems 8-64GB RAM)" | |
| else | |
| SWAP_SIZE="8G" | |
| echo "Recommended swap: ${SWAP_SIZE} (8GB minimum for systems >64GB RAM)" | |
| fi | |
| # Allow user to override | |
| read -p "Use recommended swap size (${SWAP_SIZE})? [Y/n] " -n 1 -r | |
| echo | |
| if [[ ! $REPLY =~ ^[Yy]$ ]] && [[ ! -z $REPLY ]]; then | |
| read -p "Enter desired swap size (e.g., 2G, 4G, 8G): " SWAP_SIZE | |
| fi | |
| SWAPFILE="/swapfile" | |
| # Disable existing swap | |
| echo "Disabling existing swap..." | |
| swapoff -a | |
| # Remove old swapfile if it exists | |
| if [ -f "$SWAPFILE" ]; then | |
| echo "Removing old swapfile..." | |
| rm -f "$SWAPFILE" | |
| fi | |
| # Remove swap entries from /etc/fstab | |
| sed -i '/swap/d' /etc/fstab | |
| # Create new swapfile | |
| echo "Creating ${SWAP_SIZE} swapfile..." | |
| fallocate -l "$SWAP_SIZE" "$SWAPFILE" || dd if=/dev/zero of="$SWAPFILE" bs=1M count=$((${SWAP_SIZE%G} * 1024)) | |
| # Set proper permissions | |
| chmod 600 "$SWAPFILE" | |
| # Setup swap | |
| echo "Setting up swap..." | |
| mkswap "$SWAPFILE" | |
| # Enable swap | |
| swapon "$SWAPFILE" | |
| # Make swap permanent | |
| echo "$SWAPFILE none swap sw 0 0" >> /etc/fstab | |
| # Optimize swap usage (swappiness) | |
| echo "Configuring swappiness..." | |
| sysctl vm.swappiness=10 | |
| echo "vm.swappiness=10" >> /etc/sysctl.conf | |
| echo "" | |
| echo "✓ Swap configuration complete!" | |
| echo "" | |
| swapon --show | |
| free -h |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment