Last active
February 24, 2023 01:50
-
-
Save charlieporth1/cd255cf30fa7a414b59bddbce2ee8ae6 to your computer and use it in GitHub Desktop.
Adjustable swap file creation and turn on script
This file contains 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 | |
# round $1 to $2 decimal places | |
SWAP_FILE_SIZE_INPUT="${1:-8192}" | |
SWAP_FILE_LOCATION="${2:-/swapfile}" | |
round() { | |
printf "%.${2:-0}f" "$1" | |
} | |
ROOT_STORAGE_STATS=`df -h | grep root` | |
FREE_SPACE=`df -h | grep root | awk '{print $4}'` | |
MEM_COUNT=$(round `grep MemTotal /proc/meminfo | awk '{print $2 / 1024}'` 0) | |
#Given a floating point value, we can round it trivially with printf: | |
echo $MEM_COUNT | |
#If more than 12 GB of free space and less than 4GB of ram create swap if swapfile does not exist | |
if ! [[ -f $SWAP_FILE_LOCATION ]]; then | |
echo "SWAP File does not exist creating swapfile at $SWAP_FILE_LOCATION size $SWAP_FILE_SIZE_INPUT MB" | |
touch $SWAP_FILE_LOCATION | |
SWAP_FILE_SIZE=${SWAP_FILE_SIZE_INPUT:=8192} | |
dd_cmd="sudo dd if=/dev/zero of=$SWAP_FILE_LOCATION bs=512 count=$(( $SWAP_FILE_SIZE * 2 ))K " | |
$dd_cmd status=progress || $dd_cmd | |
chmod 0600 $SWAP_FILE_LOCATION | |
fallocate -l $(( $SWAP_FILE_SIZE * 1024 ))K $SWAP_FILE_LOCATION | |
chmod 0600 $SWAP_FILE_LOCATION | |
mkswap $SWAP_FILE_LOCATION | |
chmod 0600 $SWAP_FILE_LOCATION | |
swapon $SWAP_FILE_LOCATION | |
cp /etc/fstab /etc/fstab.bak | |
[[ -z `grep -o "$SWAP_FILE_LOCATION" /etc/fstab` ]] && echo "$SWAP_FILE_LOCATION none swap sw 0 0" | tee -a /etc/fstab | |
sysctl -w vm.swappiness=25 | |
[[ -z `grep -o "vm.swappiness" /etc/sysctl.conf` ]] && echo "vm.swappiness=25" | tee -a /etc/sysctl.conf | |
elif [[ -f $SWAP_FILE_LOCATION ]]; then | |
echo "SWAP File currently exists at $SWAP_FILE_LOCATION!" | |
echo "Only running swapon" | |
swapon $SWAP_FILE_LOCATION | |
fi | |
chmod 0600 $SWAP_FILE_LOCATION | |
sysctl vm.swappiness |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run this