Enable ZRAM on Linux: compressed swap for low-RAM machines

If you want to experiment with the ZRAM feature, I have this script:

#!/bin/bash
# =============================================================================
# zram-config.sh - Init-system-agnostic ZRAM (compressed RAM swap) manager
#
# Detects and integrates with: systemd, OpenRC, runit, sysvinit.
# Falls back to direct /sys configuration with a warning if none detected.
#
# Usage:
#   zram-config.sh enable [--percent N] [--algo zstd|lz4|lz4hc] [--force]
#   zram-config.sh disable
#   zram-config.sh set-percent N
#   zram-config.sh status
#
# Auto-detection:
#   - PERCENT from RAM:  <=2GB -> 100%   <=4GB -> 75%   <=8GB -> 50%   >8GB -> 25%
#   - ALGO:              zstd > lz4hc > lz4 (whichever the kernel supports)
#
# Persistence is written per-init-system (unit/script + enable).
# Runtime uses direct /sys/block/zram0 manipulation so it works everywhere.
# =============================================================================
set -euo pipefail

SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || echo "$0")"
CONF_DIR=/etc/zram-config
CONF_FILE=$CONF_DIR/config
SYSCTL_DROPIN=/etc/sysctl.d/99zz-zram-priority.conf
SYSCTL_REVERT=/etc/sysctl.d/99-zram-reverted.conf
BACKUP_DIR="/var/backups/zram-config-$(date +%F)"
INIT=""

info() { echo ">>> $*"; }
warn() { echo "WARN: $*" >&2; }
die()  { echo "ERROR: $*" >&2; exit 1; }
require_root() { [[ $EUID -eq 0 ]] || die "must be run as root"; }

detect_init() {
    if [[ -d /run/systemd/system ]] && command -v systemctl >/dev/null; then
        echo systemd
    elif command -v rc-service >/dev/null && [[ -d /etc/runlevels ]]; then
        echo openrc
    elif command -v sv >/dev/null && { [[ -d /etc/sv ]] || [[ -d /etc/service ]] || [[ -d /var/service ]]; }; then
        echo runit
    elif command -v update-rc.d >/dev/null && [[ -d /etc/init.d ]]; then
        echo sysvinit
    else
        echo none
    fi
}

detect_percent() {
    local mem_mb
    mem_mb=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)
    if   (( mem_mb <= 2048 )); then echo 100
    elif (( mem_mb <= 4096 )); then echo 75
    elif (( mem_mb <= 8192 )); then echo 50
    else                            echo 25
    fi
}

detect_algo() {
    if modprobe -n zstd 2>/dev/null || modinfo zstd >/dev/null 2>&1; then echo zstd
    elif modprobe -n lz4hc 2>/dev/null; then echo lz4hc
    else echo lz4
    fi
}

validate_percent() {
    local p="$1"
    [[ "$p" =~ ^[0-9]+$ ]] || die "percent must be an integer"
    (( p >= 10 && p <= 200 )) || die "percent out of range (10-200)"
}

read_conf() {
    local key="$1"
    awk -F= -v k="$key" '$1==k{print $2}' "$CONF_FILE" 2>/dev/null | head -1
}

# ---------------------------------------------------------------------------
# Runtime (init-agnostic): direct /sys/block/zram0 manipulation
# ---------------------------------------------------------------------------
runtime_enable() {
    local percent="$1" algo="$2"
    local mem_bytes size_bytes

    modprobe zram 2>/dev/null || modprobe zram num_devices=1 2>/dev/null || true
    local i
    for i in 1 2 3 4 5; do
        [[ -b /dev/zram0 ]] && break
        sleep 0.2
    done
    [[ -b /dev/zram0 ]] || die "zram module failed to load (/dev/zram0 missing)"

    swapoff /dev/zram0 2>/dev/null || true
    echo 1 > /sys/block/zram0/reset 2>/dev/null || true

    if ! echo "$algo" > /sys/block/zram0/comp_algorithm 2>/dev/null; then
        warn "algorithm '$algo' not available in kernel, falling back to lz4"
        echo lz4 > /sys/block/zram0/comp_algorithm || die "cannot set comp_algorithm"
    fi

    mem_bytes=$(awk '/^MemTotal:/{print $2*1024}' /proc/meminfo)
    size_bytes=$(( mem_bytes * percent / 100 ))
    echo "$size_bytes" > /sys/block/zram0/disksize

    mkswap /dev/zram0 >/dev/null
    swapon -p 100 /dev/zram0
    info "zram0 active: ${size_bytes} bytes (${percent}% of RAM), algo=$algo, priority=100"
}

runtime_disable() {
    swapoff /dev/zram0 2>/dev/null || true
    echo 1 > /sys/block/zram0/reset 2>/dev/null || true
    modprobe -r zram 2>/dev/null || true
    info "zram0 stopped and module unloaded (if idle)"
}

# ---------------------------------------------------------------------------
# Persistence: write per-init-system unit/script
# ---------------------------------------------------------------------------
persist_systemd() {
    cat > /etc/systemd/system/zramswap.service <<EOF
[Unit]
Description=ZRAM compressed swap (managed by zram-config.sh)
After=multi-user.target
Before=swap.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$SCRIPT_PATH _boot
ExecStop=$SCRIPT_PATH _stop

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
}

persist_openrc() {
    cat > /etc/init.d/zramswap <<EOF
#!/sbin/openrc-run
description="ZRAM compressed swap (managed by zram-config.sh)"
depend() {
    after localmount
    before swap
}
start() {
    ebegin "Starting ZRAM compressed swap"
    $SCRIPT_PATH _boot
    eend \$?
}
stop() {
    ebegin "Stopping ZRAM compressed swap"
    $SCRIPT_PATH _stop
    eend \$?
}
EOF
    chmod +x /etc/init.d/zramswap
}

persist_runit() {
    mkdir -p /etc/sv/zramswap
    cat > /etc/sv/zramswap/run <<EOF
#!/bin/sh
exec 2>&1
$SCRIPT_PATH _boot
exec sleep infinity
EOF
    chmod +x /etc/sv/zramswap/run
    cat > /etc/sv/zramswap/finish <<EOF
#!/bin/sh
$SCRIPT_PATH _stop
EOF
    chmod +x /etc/sv/zramswap/finish
    # Hook into the active runsvdir (Debian: /etc/service, Void: /var/service)
    if [[ -d /etc/service ]]; then
        ln -sfn /etc/sv/zramswap /etc/service/zramswap
    elif [[ -d /var/service ]]; then
        ln -sfn /etc/sv/zramswap /var/service/zramswap
    elif [[ -d /etc/runit/runsvdir/default ]]; then
        ln -sfn /etc/sv/zramswap /etc/runit/runsvdir/default/zramswap
    fi
}

persist_sysvinit() {
    cat > /etc/init.d/zramswap <<EOF
#!/bin/sh
### BEGIN INIT INFO
# Provides:          zramswap
# Required-Start:    \$local_fs
# Required-Stop:     \$local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ZRAM compressed swap (managed by zram-config.sh)
### END INIT INFO
case "\$1" in
    start)   $SCRIPT_PATH _boot ;;
    stop)    $SCRIPT_PATH _stop ;;
    restart) $SCRIPT_PATH _stop; $SCRIPT_PATH _boot ;;
    status)  swapon --show | grep -q zram0 ;;
    *) echo "Usage: \$0 {start|stop|restart|status}"; exit 1 ;;
esac
EOF
    chmod +x /etc/init.d/zramswap
}

persist_init() {
    case "$INIT" in
        systemd)  persist_systemd ;;
        openrc)   persist_openrc ;;
        runit)    persist_runit ;;
        sysvinit) persist_sysvinit ;;
        none)     warn "no init system detected; zram will be started now but NOT persist across reboots" ;;
    esac
}

# ---------------------------------------------------------------------------
# Service control (per init system)
# ---------------------------------------------------------------------------
svc_enable() {
    case "$INIT" in
        systemd)  systemctl enable zramswap.service >/dev/null 2>&1; systemctl start zramswap.service ;;
        openrc)   rc-update add zramswap default >/dev/null 2>&1; rc-service zramswap start ;;
        runit)    sv start zramswap 2>/dev/null || sv start /etc/sv/zramswap 2>/dev/null || "$SCRIPT_PATH" _boot ;;
        sysvinit) update-rc.d zramswap defaults >/dev/null 2>&1; /etc/init.d/zramswap start ;;
        none)     "$SCRIPT_PATH" _boot ;;
    esac
}

svc_disable() {
    case "$INIT" in
        systemd)  systemctl disable --now zramswap.service 2>/dev/null || true; rm -f /etc/systemd/system/zramswap.service; systemctl daemon-reload ;;
        openrc)   rc-service zramswap stop 2>/dev/null || true; rc-update del zramswap default 2>/dev/null || true; rm -f /etc/init.d/zramswap ;;
        runit)    sv down zramswap 2>/dev/null || sv down /etc/sv/zramswap 2>/dev/null || true; rm -f /etc/service/zramswap /var/service/zramswap /etc/runit/runsvdir/default/zramswap 2>/dev/null; rm -rf /etc/sv/zramswap ;;
        sysvinit) /etc/init.d/zramswap stop 2>/dev/null || true; update-rc.d -f zramswap remove 2>/dev/null || true; rm -f /etc/init.d/zramswap ;;
        none)     "$SCRIPT_PATH" _stop ;;
    esac
}

svc_restart() {
    case "$INIT" in
        systemd)  systemctl restart zramswap.service ;;
        openrc)   rc-service zramswap restart ;;
        runit)    sv restart zramswap 2>/dev/null || { "$SCRIPT_PATH" _stop; "$SCRIPT_PATH" _boot; } ;;
        sysvinit) /etc/init.d/zramswap restart ;;
        none)     "$SCRIPT_PATH" _stop; "$SCRIPT_PATH" _boot ;;
    esac
}

# ---------------------------------------------------------------------------
# Config + sysctl
# ---------------------------------------------------------------------------
write_config() {
    local percent="$1" algo="$2"
    mkdir -p "$CONF_DIR"
    cat > "$CONF_FILE" <<EOF
# Managed by zram-config.sh on $(date +%F)
PERCENT=$percent
ALGO=$algo
PRIORITY=100
EOF
}

write_sysctl() {
    cat > "$SYSCTL_DROPIN" <<'EOF'
# zram tuning: prefer compressing cold pages to zram (priority 100 beats disk swap)
vm.swappiness = 100
vm.page-cluster = 0
EOF
    rm -f "$SYSCTL_REVERT"
    sysctl --system >/dev/null 2>&1 || true
}

revert_sysctl() {
    rm -f "$SYSCTL_DROPIN"
    cat > "$SYSCTL_REVERT" <<'EOF'
vm.swappiness = 60
EOF
    sysctl --system >/dev/null 2>&1 || true
}

backup_existing() {
    mkdir -p "$BACKUP_DIR"
    local f
    for f in "$CONF_FILE" "$SYSCTL_DROPIN" /etc/systemd/system/zramswap.service \
             /etc/init.d/zramswap /etc/sv/zramswap "$SYSCTL_REVERT"; do
        [[ -e "$f" ]] && cp -a "$f" "$BACKUP_DIR/" 2>/dev/null || true
    done
    [[ -d /etc/sv/zramswap ]] && cp -a /etc/sv/zramswap "$BACKUP_DIR/" 2>/dev/null || true
    info "Backups (if any) in $BACKUP_DIR"
}

# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
cmd_enable() {
    local percent="" algo="" force=0
    while (( $# )); do
        case "$1" in
            --percent) percent="${2:-}"; shift 2 ;;
            --algo)    algo="${2:-}";    shift 2 ;;
            --force)   force=1; shift ;;
            *) die "unknown option: $1" ;;
        esac
    done
    require_root
    backup_existing
    percent="${percent:-$(detect_percent)}"
    algo="${algo:-$(detect_algo)}"
    validate_percent "$percent"

    if [[ -f "$CONF_FILE" ]] && (( ! force )); then
        local cur_p cur_a
        cur_p=$(read_conf PERCENT); cur_a=$(read_conf ALGO)
        if [[ "$cur_p" == "$percent" && "$cur_a" == "$algo" ]]; then
            info "already configured (PERCENT=$percent ALGO=$algo); use --force to reapply"
        fi
    fi

    info "init system detected: $INIT"
    info "applying runtime: PERCENT=$percent ALGO=$algo"
    runtime_enable "$percent" "$algo"
    write_config "$percent" "$algo"
    write_sysctl
    persist_init
    svc_enable
    info "--- status after enable ---"
    cmd_status
}

cmd_disable() {
    require_root
    backup_existing
    info "disabling zram (init: $INIT)"
    svc_disable
    runtime_disable
    rm -f "$CONF_FILE"
    rmdir "$CONF_DIR" 2>/dev/null || true
    revert_sysctl
    info "--- status after disable ---"
    swapon --show || true
    free -m
}

cmd_set_percent() {
    local percent="${1:-}"
    [[ -n "$percent" ]] || die "usage: $0 set-percent N"
    validate_percent "$percent"
    require_root
    [[ -f "$CONF_FILE" ]] || die "$CONF_FILE not found, run 'enable' first"
    info "updating PERCENT=$percent (init: $INIT)"
    sed -i "s/^PERCENT=.*/PERCENT=$percent/" "$CONF_FILE"
    grep -q '^ALGO='     "$CONF_FILE" || echo "ALGO=$(detect_algo)" >> "$CONF_FILE"
    grep -q '^PRIORITY=' "$CONF_FILE" || echo "PRIORITY=100"        >> "$CONF_FILE"
    svc_restart
    sleep 1
    cmd_status
}

cmd_status() {
    echo "=== init system: $INIT ==="
    echo "=== $CONF_FILE ==="
    cat "$CONF_FILE" 2>/dev/null || echo "(not present)"
    echo
    echo "=== sysctl ==="
    sysctl vm.swappiness vm.page-cluster 2>/dev/null || true
    echo
    echo "=== persistence ($INIT) ==="
    case "$INIT" in
        systemd)  systemctl is-enabled zramswap.service 2>/dev/null || echo "(not enabled)" ;;
        openrc)   rc-update show 2>/dev/null | grep zramswap || echo "(not enabled)" ;;
        runit)    ls -la /etc/service/zramswap /var/service/zramswap 2>/dev/null || echo "(not linked)" ;;
        sysvinit) ls /etc/rc*.d/ 2>/dev/null | grep -i zramswap || echo "(not enabled)" ;;
        none)     echo "(no init system)" ;;
    esac
    echo
    echo "=== zramctl ==="
    zramctl --output-all 2>/dev/null || echo "(not available)"
    echo
    echo "=== swapon ==="
    swapon --show || true
    echo
    echo "=== free -m ==="
    free -m
}

# Internal: called by the init script/unit
cmd_boot() {
    local percent algo
    percent=$(read_conf PERCENT)
    algo=$(read_conf ALGO)
    [[ -z "$percent" ]] && { warn "no config in $CONF_FILE"; exit 1; }
    runtime_enable "$percent" "${algo:-lz4}"
}

cmd_stop() {
    runtime_disable
}

# ---------------------------------------------------------------------------
main() {
    INIT=$(detect_init)
    local cmd="${1:-}"
    if [[ -z "$cmd" ]]; then
        echo "Usage: $0 {enable [--percent N] [--algo zstd|lz4|lz4hc] [--force] | disable | set-percent N | status}"
        exit 1
    fi
    shift || true
    case "$cmd" in
        enable)        cmd_enable "$@" ;;
        disable)       cmd_disable ;;
        set-percent)   cmd_set_percent "$@" ;;
        status)        cmd_status ;;
        _boot)         cmd_boot ;;
        _stop)         cmd_stop ;;
        *) echo "Unknown command: $cmd"; exit 1 ;;
    esac
}

main "$@"

The script is init-agnostic, works with openrc or systemd, runit and sysvinit

Run it as root with the argument "enable" to activate it or "disable" if you want to stop using it, use "status" to see the actual status

Depending of our experiencies using it, it may be a good thing to include by default on Elive :applause:

Nice, I'll runs it next weekend in both HP Mini 32 bit and Acer Aspire 64 bit, with only 2 GB RAM those laptops (from 2007 and 2012) would be a good tests machines.

BTW I have some issues to report you in my main machine, I'll do it also next weekend.

Greetings

Nice ! Thank you, I will testing.

Note that if you do have a physical swap device, zswap is considered better than zram: Debunking zswap and zram myths

Cool script, @Thanatermesis! Another thing to consider, though....

If you're going to "experiment" with zram, be sure to get some insurance by installing and/or setting up a preemptive OOM killer. While systemd has systemd-oomd, earlyoom seems to be considered a better choice, and works across inits.

Please read Chris Down's excellent (but long) article that @TheTechRobo posted above to understand why you need to do the earlyoom thing.

I generally enable zswap on most of my distros, with a dedicated swap file large enough to allow hibernation, but in reality I never hibernate. If you use zram, apparently you still can sleep, but not hibernate. In reading the Down post, it was interesting to find out that Fedora uses zram with a maximum (100%!) memory percentage as its default. No swap. THAT might be worth experimenting with for me.

I do use zram on my itty-bitty 2 GB RAM HP Stream 13 netbook with a pitiful CPU and 30 GB eMMC "SSD". I've got the %RAM set to 150 (3 GB) and use lz4 compressor since the CPU is pathetic and while lz4 doesn't compress as much as zstd (which I use on my laptop), it's faster.