Pieds-Nus_custom-scripts/swapctl.sh

60 lines
1.6 KiB
Bash

#!/bin/bash
usage="$0 -d DIR -n NAME -s SIZE -p PRIO add|remove
Add or remove swapfiles to micro-manage disk usage.
-d DIR : set DIRectory to place swapfile in. Default: /mnt
-n NAME : set filename for the swapfile. Default: swapfileN
-s SIZE : SIZE in MB (only when creating a swapfile). Default: 1024
-p PRIO : Priority to use with swapon. Range from 0 to 1000. Default: 500
-h : Display this help and exit."
test $# -eq 0 && ( echo -e "$usage" ; echo "You must provide either 'add' or 'remove' !" ; exit 1 )
SWAP_FOLDER="/mnt"
SWAP_FILENAME="swapfile"
SWAP_SIZE="12" #in MB
SWAP_PRIO_MAX=500 #range 0..1000
SWAP_PRIO_INC=10
while getopts hp:s:n:d: arg ; do
case $arg in
h) echo -e "$usage" ; exit 0 ;;
d) SWAP_FOLDER="$OPTARG" ;;
n) SWAP_FILENAME="$OPTARG" ;;
s) SWAP_SIZE="$OPTARG" ;;
p) SWAP_PRIO_MAX="$OPTARG" ;;
*) echo -e "$usage" ; echo "Invalid option: $arg"; exit 1 ;;
esac
done
shift $((( $OPTIND - 1 )))
if test "$1" = "add" ; then
N=$(ls $SWAP_FOLDER/$SWAP_FILENAME* | wc -l)
swapfile=$SWAP_FOLDER/$SWAP_FILENAME$N
echo "Creating swapfile: $swapfile"
sudo dd if=/dev/urandom of=$swapfile bs=1M count=$SWAP_SIZE status=progress
sudo chmod 0600 $swapfile
sudo mkswap $swapfile
sudo swapon -p $((($SWAP_PRIO_MAX - $N * $SWAP_PRIO_INC))) $swapfile
echo -e "\n\n\n\n"
sudo swapon
elif test "$1" = "remove" ; then
N=$(ls $SWAP_FOLDER/$SWAP_FILENAME* | wc -l)
swapfile=$SWAP_FOLDER/$SWAP_FILENAME$((($N - 1)))
echo "Removing swapfile: $swapfile"
sudo swapoff $swapfile && sudo rm $swapfile
echo -e "\n\n\n\n"
sudo swapon
fi