user2650277
user2650277

Reputation: 6739

Check if swap space exist in bash

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

Upvotes: 4

Views: 3983

Answers (2)

Emmet
Emmet

Reputation: 6421

This works nicely for me:

if free | awk '/^Swap:/ {exit !$2}'; then
    echo "Have swap"
else
    echo "No swap"
fi

Upvotes: 11

Dale_Reagan
Dale_Reagan

Reputation: 2061

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

Upvotes: 1

Related Questions