Skip to content

Instantly share code, notes, and snippets.

@ivuorinen
Created January 2, 2019 13:17
Show Gist options
  • Save ivuorinen/a5d5506d56ba32bfa33a4dbc0a68da80 to your computer and use it in GitHub Desktop.
Save ivuorinen/a5d5506d56ba32bfa33a4dbc0a68da80 to your computer and use it in GitHub Desktop.
swapfile automation
#!/bin/bash
# Swapfile generator
#
# Copyright 2019 Ismo Vuorinen <[email protected]>
# Licensed under MIT <https://opensource.org/licenses/MIT>
_err () {
echo "(!) Error: $1" >&2; exit 1
}
# Check that the user is logged in as root
if [[ $(id -u) -ne 0 ]] ; then _err "Please run as root" ; fi
_command_exists () {
type "$1" &> /dev/null;
}
# Check that our system has all the required commands available
required_applications=( "dd" "chown" "chmod" "swapon" "mkswap" )
for i in "${required_applications[@]}"
do
if ! _command_exists "$i"; then
_err "I require $i but it's not installed. Aborting."
fi
done
# Get arguments
while getopts s:f: option
do
case "${option}"
in
s) SIZE=${OPTARG};;
f) FILE=$OPTARG;;
*) echo "$0 -s (Size in GB) -f (Full path to swap file)";;
esac
done
# Check that the size given is a number
reSize='^[0-9]+$'
if ! [[ $SIZE =~ $reSize ]] ; then
_err "Swap size (-s) was not a number! Aborting."
fi
# No filename was given, use default (/swapfile-YYYY-MM)
if [ -z "$FILE" ]; then
FILE="/swapfile-$(date +%Y-%m)"
fi
# Check that we are not accidentally overriding anything
if [ -f "$FILE" ]; then
_err "File $FILE already exists! Aborting."
fi
# Fix variables for commands
FILESIZE=$((SIZE*1024*1024))
FILE=$(realpath "$FILE")
# The filename is empty, how about that?
if ! [ "$FILE" ]; then
_err "Something went wrong"
fi
SLASHES=$(echo "${FILE}" | awk -F"/" '{print NF-1}')
if ! [[ $SLASHES == 1 ]] ; then
_err "You should use root path, not inside subfolders. (Slashes in $FILE = $SLASHES)"
fi
echo
echo "Changes about to be made:"
echo " -> Swap file: $FILE"
echo " -> Swap size: $SIZE GB ($FILESIZE bytes)"
echo " -> Change ownership to root:root and make it writable only to root"
echo " -> mkswap and swapon"
echo " -> Add it to /etc/fstab to persist the change across boots"
echo " -> List swapfiles present on the system"
echo
read -p "Continue and make changes? [y/N] " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
dd if=/dev/zero of="$FILE" bs=1024 count=$FILESIZE \
&& chown root:root "$FILE" \
&& chmod 0600 "$FILE" \
&& mkswap "$FILE" \
&& swapon "$FILE" \
&& echo "$FILE none swap sw 0 0" >> /etc/fstab \
&& swapon -s
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment