Skip to content

Instantly share code, notes, and snippets.

@SuperPaintman
Last active September 13, 2016 01:44
Show Gist options
  • Save SuperPaintman/f828a615c64d6653eaa56c8944169ddd to your computer and use it in GitHub Desktop.
Save SuperPaintman/f828a615c64d6653eaa56c8944169ddd to your computer and use it in GitHub Desktop.
#!/bin/bash
if [[ $(swapon -s) != "" && $(swapon -s | wc -l) != 0 ]]; then
echo "Swap already created"
exit 1
fi
SWAP_FILENAME="/swapfile"
mem_size="$(free | grep -i 'mem:' | awk '{ print $2 }')"
if [[ "$mem_size" -gt "$((64 * 1024 * 1024))" ]]; then
recommended_swap_size="$((4 * 1024 * 1024))"
elif [[ "$mem_size" -gt "$((8 * 1024 * 1024))" ]]; then
recommended_swap_size="$((mem_size / 2))"
elif [[ "$mem_size" -gt "$((2 * 1024 * 1024))" ]]; then
recommended_swap_size="$((mem_size))"
else
recommended_swap_size="$((mem_size * 2))"
fi
recommended_swap_size=${recommended_swap_size%.*}
dd if=/dev/zero of=$SWAP_FILENAME bs=1024 "count=$recommended_swap_size"
chown root:root $SWAP_FILENAME
chmod 0600 $SWAP_FILENAME
mkswap $SWAP_FILENAME
swapon $SWAP_FILENAME
echo "# Swap" >> /etc/fstab
echo "$SWAP_FILENAME none swap sw 0 0" >> /etc/fstab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment