Created
May 19, 2015 13:15
-
-
Save iamtew/a3375f0050ed1c4935aa to your computer and use it in GitHub Desktop.
Function to create and configure swap file on Linux. Useful on VPS' and the like where images normally don't come configured with swap by default.
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 | |
test "$(id -u)" -eq 0 || exit 1 | |
# Create and configurat swapfile | |
create_add_swapfile() { | |
test -z $1 && return 1 | |
local size=$(echo ${1} | grep -o -E '^[0-9]*') | |
local unit=$(echo ${1} | grep -o -E '[^0-9](.*)?$' || echo M) | |
local file="/swapfile.${size}${unit}" | |
if [[ -f "$file" ]]; then | |
echo "Error: File exists: ${file}" >&2 | |
return 1 | |
fi | |
# Create the actual file | |
fallocate -l "${size}${unit}" "${file}" | |
chmod 0600 "${file}" | |
chown root:root "${file}" | |
mkswap "${file}" | |
swapon "${file}" | |
# Comment out existing entry in /etc/fstab | |
sed -i -e "/^\\${file}/s/^/#/" /etc/fstab | |
printf "%s\tnone\tswap\tdefaults\t0 0\n" ${file} >> /etc/fstab | |
} | |
grep -q -E '^SwapTotal: * 0 kB' /proc/meminfo | |
test $? -eq 0 \ | |
&& create_add_swapfile 1024MiB | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment