Parker Wedge Parker Wedge - 1 year ago 46
Bash Question

Bash script ignores if, then statement; returns the same result every time

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
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.

# 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;

sed -n '4p' info > swapline
less swapline | while read -a bytes;

diff=$((avail - swap))

if (( diff > 128 )); then
echo "unswapping"
swapoff -a
swapon /dev/sda2
echo "Not enough room in memory to unswap"

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

Answer Source

As @thatotherguy pointed out, the avail and swap variables are not set in the same scope, due to the pipe to the while loops. Change the loops like so:

while read -a bytes
done < swapline