Workaround for "swapon failed: invalid argument"
#!/bin/bash
# #####################################
# Script: Swap Creator v1.1
# Description: Creates swap file on cache to reduce RAM usage
# Author: Marc Gutt
# edited by: Hugo Martins
# ######### Settings ##################
swapfile='/mnt/cache/swapfile'
swapfile_size=6G
# #####################################
#
# ######### Script ####################
# make script race condition safe
if [[ -d "/tmp/${0///}" ]] || ! mkdir "/tmp/${0///}"; then exit 1; fi; trap 'rmdir "/tmp/${0///}"' EXIT;
# create swap file https://linuxize.com/post/create-a-linux-swap-file/
if ! [ -f "$swapfile" ]; then
#fallocate -l "$swapfile_size" "$swapfile"
truncate -s 0 "$swapfile"
chattr +C "$swapfile"
btrfs property set "$swapfile" compression none
dd if=/dev/zero of="$swapfile" bs=1M count=6144 status=progress
chmod 600 "$swapfile"
mkswap "$swapfile"
echo "Swap file created"
else
echo "Swap file already exists"
fi
# enable swap
if [[ $(swapon --show) == *"${swapfile}"* ]]; then
echo "Swap is already enabled"
else
swapon "$swapfile"
echo "Swap has been enabled"
echo "Finally, edit the fstab configuration to add an entry for the swap file:"
echo "nano /etc/fstab"
echo "to add"
echo "/swapfile none swap defaults 0 0"
fi
After running:
total used free shared buff/cache available
Mem: 15Gi 5.0Gi 409Mi 1.0Gi 10Gi 9.3Gi
Swap: 6.0Gi 16Mi 6.0Gi