- Bash
- mkfswap.sh
Swap file. Good for VM that has no Swap assigned.
- mkfswap.sh
wget -q https://kps.makz.net/run/mkfswap.sh -O - | bash
#!/bin/bash
#
# Create and enable a swap file.
#
set -euo pipefail
readonly SWAPFILE="/swapfile"
readonly SIZE_GB="${1:-2}"
readonly FSTAB_LINE="${SWAPFILE} none swap sw 0 0"
die() { echo "Error: $*" >&2; exit 1; }
info() { echo "$*"; }
# ---------- preflight ----------
[[ $EUID -eq 0 ]] || die "Must be run as root."
[[ "$SIZE_GB" =~ ^[0-9]+$ ]] && (( SIZE_GB > 0 )) \
|| die "Size must be a positive integer (GB). Got: $SIZE_GB"
if [[ -e "$SWAPFILE" ]]; then
info "Swap file ${SWAPFILE} already exists."
swapon --show
exit 0
fi
# ---------- free-space check ----------
# Need SIZE_GB * 1024 * 1024 KiB free on the target filesystem.
need_kib=$(( SIZE_GB * 1024 * 1024 ))
avail_kib=$(df -Pk -- "$(dirname "$SWAPFILE")" | awk 'NR==2 {print $4}')
(( avail_kib >= need_kib )) \
|| die "Not enough free space: need ${need_kib} KiB, have ${avail_kib} KiB."
# ---------- create ----------
info "Allocating ${SIZE_GB}G at ${SWAPFILE}..."
if command -v fallocate >/dev/null && fallocate -l "${SIZE_GB}G" "$SWAPFILE" 2>/dev/null; then
: # fast path on ext4/xfs/btrfs
else
# Fallback for filesystems where fallocate is unsupported (e.g. some tmpfs/zfs setups).
rm -f "$SWAPFILE"
dd if=/dev/zero of="$SWAPFILE" bs=1M count="$(( SIZE_GB * 1024 ))" status=progress
fi
chmod 600 "$SWAPFILE"
mkswap "$SWAPFILE"
swapon "$SWAPFILE"
# ---------- persist in fstab ----------
if grep -qE "^[[:space:]]*${SWAPFILE}[[:space:]]" /etc/fstab; then
info "fstab entry for ${SWAPFILE} already present."
else
info "Adding fstab entry: ${FSTAB_LINE}"
printf '%s\n' "$FSTAB_LINE" >> /etc/fstab
fi
swapon --show --bytes
info "Done."