Add script to easily make a swapfile
authorMichael Brown <michael.brown@discourse.org>
Tue, 22 Apr 2014 13:54:18 +0000 (09:54 -0400)
committerMichael Brown <michael.brown@discourse.org>
Tue, 22 Apr 2014 13:54:18 +0000 (09:54 -0400)
scripts/mk_swapfile [new file with mode: 0755]

diff --git a/scripts/mk_swapfile b/scripts/mk_swapfile
new file mode 100755 (executable)
index 0000000..f287199
--- /dev/null
@@ -0,0 +1,44 @@
+#!/bin/bash -e
+# This script adds a 512MB swapfile to the system
+
+function do_err() {
+    code=$?
+    echo "Command failed with code $code: $BASH_COMMAND"
+    exit $code
+
+}
+trap do_err ERR
+
+
+function set_swappiness() {
+  if ! grep -q '^vm.swappiness' /etc/sysctl.conf; then
+    echo -n 'Setting '
+    sysctl -w vm.swappiness=10
+    echo vm.swappiness = 10 >> /etc/sysctl.conf
+  fi
+}
+
+function get_new_swapfile() {
+  for i in `seq 0 99`; do
+    if [ ! -e /swapfile.$i ]; then
+      echo /swapfile.$i
+      return
+    fi
+  done
+  # Seriously? 100 swapfiles already exist?
+  echo "too many swapfiles"
+  exit 1
+}
+
+[ `id -u` -eq 0 ] || { echo "You must be root to run this script"; exit 1; }
+set_swappiness
+
+SWAPFILE=$(get_new_swapfile)
+
+umask 077
+dd if=/dev/zero of=$SWAPFILE bs=1k count=512k conv=excl
+mkswap $SWAPFILE
+swapon $SWAPFILE
+echo "$SWAPFILE swap swap auto 0 0" >> /etc/fstab
+
+echo 512MB swapfile successfully added