4

I want to check whether Swap space exist on a centos box in my bash script.Thus in cash there are no swap space on the server , then i can create swap.

I tried this approach

if [[ -n $(swapon -s) ]]; then
    :
else
   mkswap /dev/vda2 &> /dev/null
   swapon /dev/vda2
fi

Obviously it won't work since even when there is no swap swapon -s will return a string Filename Type Size Used Priority

user2650277
  • 6,289
  • 17
  • 63
  • 132

2 Answers2

10

This works nicely for me:

if free | awk '/^Swap:/ {exit !$2}'; then
    echo "Have swap"
else
    echo "No swap"
fi
Emmet
  • 6,192
  • 26
  • 39
1

I don't see a means to do this just using 'swapon' since it: - always returns at least one line - always returns an error code of '0'

You could 'count lines' and if less then 2 then take the 'else' branch, i.e.

if [[ $(swapon -s | wc -l) -gt 1 ]] ; then echo "OK" ; else echo "Bad" ; fi

OK

if [[ $(swapon -s | wc -l) -gt 2 ]] ; then echo "OK" ; else echo "Bad" ; fi

Bad

Or simply check for 'devices' in the swapon output, i.e.:

if [[ $(swapon -s | grep -ci "/dev" ) -gt 0 ]] ;  then echo "OK" ; else echo "Bad" ; fi
Dale_Reagan
  • 1,953
  • 14
  • 11