Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if swap space exist in bash

Tags:

bash

swapfile

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

like image 807
user2650277 Avatar asked Mar 21 '23 05:03

user2650277


2 Answers

This works nicely for me:

if free | awk '/^Swap:/ {exit !$2}'; then
    echo "Have swap"
else
    echo "No swap"
fi
like image 63
Emmet Avatar answered Mar 28 '23 02:03

Emmet


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
like image 33
Dale_Reagan Avatar answered Mar 28 '23 03:03

Dale_Reagan