I wrote a short script to compare the amount of available RAM as reported by the free -m
command with the amount of swap used and, if there is enough room for the swap + 128M (to compensate for momentary increases in swap use at the exact time the command is issued), move the swapped data back into RAM. The problem is that no matter how much RAM I'm using, the script returns "Not enough room in memory to unswap". I put echo
commands in and the math works, so I thin it's something to do with the if ((diff > 128)); then
line. I'd appreciate it if someone could take a look.
Note: I want to use the script with a cron job on a virtualization server to return KVM machines that have been swapped out to memory if there's room. Since my server is also where I try out new distros, my RAM usage tends to have periodic spikes. Consequently, seldomly used VMs like ownCloud get swapped out occasionally but don't come back in until I or someone else needs them for something, and then I get complaints that they're broken or painfully slow.
#!/bin/bash
# This script moves data from swap back into RAM
meminfo=$(mktemp -d -t meminfo.XXXXXX)
cd $meminfo
info=$(mktemp info.XXXXXX)
swapline=$(mktemp swapline.XXXXXX)
freeline=$(mktemp freeline.XXXXXX)
free -m > info
exec 0< info
sed -n '2p' info > freeline
less freeline | while read -a values;
do
free=${values[3]}
cached=${values[6]}
avail=$[$free+$cached]
done
sed -n '4p' info > swapline
less swapline | while read -a bytes;
do
swap=${bytes[2]};
done
diff=$((avail - swap))
if (( diff > 128 )); then
echo "unswapping"
swapoff -a
swapon /dev/sda2
else
echo "Not enough room in memory to unswap"
fi
rm -r $meminfo
#
Here's the current output of free -m
; the script still doesn't work.
total used free shared buffers cached
Mem: 3019 2930 88 12 49 851
-/+ buffers/cache: 2029 989
Swap: 1928 165 1763