← Back

Set up swap

Creates a swap file of the given size at /swapfile, adds it to fstab for boot, and lowers swappiness to 10.

Root required

One-line run

curl -fsSL https://www.moiu.cn/scripts/swap-setup.sh | bash

Source

#!/usr/bin/env bash
# 创建 / 调整 Swap
#
# 需要 root。默认在 /swapfile 建 2G 交换文件,已存在就先关闭再重建。
# 同时把 vm.swappiness 调到 10 —— 服务器上更愿意用内存而不是交换。
# 用法:bash swap-setup.sh [大小GB]      例:bash swap-setup.sh 4

set -e

# 需要 root:下面的系统级改动都直接执行,不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
    echo '[!] 这个脚本需要 root 权限,请用 sudo 重新运行:'
    echo '    curl -fsSL 脚本地址 | sudo bash'
    echo '    或已经下载到本地:sudo bash 本文件'
    exit 1
fi


SIZE=2
if [ "$#" -ge 1 ]; then
    SIZE="$1"
fi

SWAPFILE=/swapfile

case "$SIZE" in
    ''|*[!0-9]*) echo "[!] 大小要是整数 GB,收到:$SIZE"; exit 1 ;;
esac
if [ "$SIZE" -lt 1 ]; then
    echo '[!] 大小至少 1 GB'
    exit 1
fi

echo "====== 配置 Swap:$SIZE GB ======"

if [ -e "$SWAPFILE" ]; then
    echo '[*] 已存在交换文件,先关闭'
    swapoff "$SWAPFILE" 2>/dev/null || true
    rm -f "$SWAPFILE"
fi

echo '[*] 创建交换文件(fallocate 不行就退回 dd,稍慢)...'
if ! fallocate -l "$SIZE"G "$SWAPFILE" 2>/dev/null; then
    dd if=/dev/zero of="$SWAPFILE" bs=1M count=$((SIZE * 1024)) status=progress
fi

chmod 600 "$SWAPFILE"
mkswap "$SWAPFILE" >/dev/null
swapon "$SWAPFILE"

if ! grep -q "^$SWAPFILE" /etc/fstab; then
    printf '%s none swap sw 0 0\n' "$SWAPFILE" >> /etc/fstab
    echo '[*] 已写入 /etc/fstab(开机自动挂载)'
fi

if [ ! -f /etc/sysctl.d/99-swappiness.conf ]; then
    printf 'vm.swappiness = 10\n' > /etc/sysctl.d/99-swappiness.conf
    sysctl --system >/dev/null
    echo '[*] vm.swappiness 已设为 10'
fi

echo ''
echo '====== 当前 Swap ======'
swapon --show
free -h

Download the raw file