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
This works nicely for me:
if free | awk '/^Swap:/ {exit !$2}'; then
echo "Have swap"
else
echo "No swap"
fi
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With