Last active
August 19, 2020 02:52
-
-
Save und3fined/9390487c674d78c840065e999c9cf1c2 to your computer and use it in GitHub Desktop.
How to Add Swap Space on CentOS 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Make swap space | |
# ---------------- | |
# How to use? | |
# Create add-swap.sh file with this content | |
# chmod +x add-swap.sh | |
# Run: ./add-swap.sh | |
if [[ $EUID -ne 0 ]]; then | |
echo "Please execute script with a superuser..." 1>&2 | |
exit 1 | |
fi | |
SWAP_PATH=/swapfile | |
# DEBUG | |
#rm -rf $SWAP_PATH | |
if test -f "$SWAP_PATH"; then | |
echo "$SWAP_PATH exists." | |
exit 1 | |
fi | |
echo "Start create Swap Space to $SWAP_PATH" | |
#============================================ | |
echo "Tell me size for Swap Space." | |
echo "Use Gigabyte unit. Ex: enter 4 for 4G" | |
until [[ $SWAP_SIZE =~ ^[0-9]+$ ]]; do | |
read -rp "Swap size: " -e SWAP_SIZE | |
done | |
SWAP_UNIT_SHORT="G" | |
SWAP_UNIT="GB" | |
echo "Create $SWAP_PATH with size: $SWAP_SIZE$SWAP_UNIT" | |
#============================================ | |
FALLOCATE_CMD=$(fallocate -l $SWAP_SIZE$SWAP_UNIT_SHORT /swapfile) | |
if [[ -z "$FALLOCATE_CMD" ]]; then | |
dd if=/dev/zero of=$SWAP_PATH bs=1024 count=$((1024 * 1024 * $SWAP_SIZE)) | |
fi | |
#=========================================== | |
chmod 600 $SWAP_PATH | |
mkswap $SWAP_PATH | |
swapon $SWAP_PATH | |
swapon --show | |
free -m | |
#=========================================== | |
echo "Set swap piness to 15" | |
sysctl vm.swappiness=15 | |
echo "vm.swappiness=15" >> /etc/sysctl.conf | |
echo "" | |
echo "=========== DONE ============" | |
echo "" | |
#========================================== | |
echo "NOTE:" | |
echo "Manual add swap start with startup to /etc/fstab" | |
echo "$SWAP_PATH swap swap defaults 0 0" | |
echo "" | |
echo "For removing Swap" | |
echo "swapoff -v $SWAP_PATH" | |
echo "rm -rf $SWAP_PATH" | |
echo "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment