3 # File: live-swapfile - create and use a swap file
4 # Copyright: (C) 2009 Daniel Baumann <daniel@debian.org>
10 _SWAP_DIRECTORY
="${_SWAP_DIRECTORY:-/live/swap}"
11 _SWAP_FILE
="${_SWAP_FILE:-swapfile.img}"
13 _SWAP_SIZE
="${_SWAP_SIZE:-auto}"
14 _SWAP_FACTOR
="${_SWAP_FACTOR:-2}"
16 _SWAP_PURGE
="${_SWAP_PURGE:-true}"
17 _FORCE
="${_FORCE:-true}"
21 # Reading size of physical memory
22 _MEM_TOTAL_KB
="$(awk '/^MemTotal: / { print $2 }' /proc/meminfo)"
23 _MEM_TOTAL_MB
="$(expr ${_MEM_TOTAL_KB} / 1024)"
25 echo "Found ${_MEM_TOTAL_MB} MB physical memory."
27 # Setting size of new swapfile
28 if [ -z "${_SWAP_SIZE}" ] ||
[ "${_SWAP_SIZE}" = "auto" ]
30 _SWAP_SIZE_KB
="$(expr ${_MEM_TOTAL_KB} '*' ${_SWAP_FACTOR})"
31 _SWAP_SIZE_MB
="$(expr ${_SWAP_SIZE_KB} / 1024)"
33 _SWAP_SIZE_MB
="${_SWAP_SIZE}"
36 echo "Requesting ${_SWAP_SIZE_MB} MB swapfile."
38 # Reading size of old swapfile
39 if [ -e "${_SWAP_DIRECTORY}/${_SWAP_FILE}" ]
41 _SWAP_FILESIZE
="$(ls -hl ${_SWAP_DIRECTORY}/${_SWAP_FILE} | awk '{ print $5 }')"
43 echo "Found ${_SWAP_FILESIZE} MB swapfile."
46 # Creating new swap file
47 if [ "${_SWAP_FILESIZE}" != "${_SWAP_SIZE_MB}M" ]
49 if [ "${_FORCE}" = "true" ]
51 # Removing old swapfile
52 rm -f "${_SWAP_DIRECTORY}/${_SWAP_FILE}"
54 echo "Creating ${_SWAP_SIZE_MB} MB swapfile."
56 mkdir
-p "${_SWAP_DIRECTORY}"
58 # Unfortunately, swapon does not support files
59 # with holes, therefore we cannot preallocate.
60 dd if=/dev
/zero of
="${_SWAP_DIRECTORY}/${_SWAP_FILE}" bs=1024k count="${_SWAP_SIZE_MB}"
67 echo "Enabling ${_SWAP_DIRECTORY}/${_SWAP_FILE}."
69 mkswap
"${_SWAP_DIRECTORY}/${_SWAP_FILE}"
70 swapon
"${_SWAP_DIRECTORY}/${_SWAP_FILE}"
74 if grep -qs "${_SWAP_DIRECTORY}/${_SWAP_FILE}" /proc
/swaps
76 echo "Disabling ${_SWAP_DIRECTORY}/${_SWAP_FILE}."
78 swapoff
"${_SWAP_DIRECTORY}/${_SWAP_FILE}"
81 if [ "${_SWAP_PURGE}" = "true" ]
83 echo "Removing ${_SWAP_DIRECTORY}/${_SWAP_FILE}."
85 rm -f "${_SWAP_DIRECTORY}/${_SWAP_FILE}"
87 __DIRECTORY
="${_SWAP_DIRECTORY}"
88 while [ "${__DIRECTORY}" != "/" ]
90 rmdir --ignore-fail-on-non-empty "${__DIRECTORY}"
91 __DIRECTORY
="$(dirname ${__DIRECTORY})"
97 echo "Usage: ${0} {add|remove}"