1

I am looking for a script that tests for swap and exits gracefully if swap is found as part of this script:

#!/bin/bash
# This script formats and mounts /dev/sdc

{
if [ ! -f /scripts/alert ]; then
    echo "File not found!"
    exit 0
fi
} 

mkswap /dev/sdc && swapon /dev/sdc

#END
2
  • 1
    "cat /proc/swaps" should help you
    – maxxvw
    Mar 11, 2014 at 16:32
  • I thought of that, but I doubt that would work in a if else statement
    – Peter
    Mar 11, 2014 at 18:44

2 Answers 2

3

Lacking a swapinfo (*BSD) ,swapon -s (swap usage) is the next best thing.

Any of the following should do the trick, setting $? to 0 if one or more swaps are set up:

/sbin/swapon -s | grep -q /dev
grep -q /dev /proc/swaps
free | awk '/Swap/{ exit(!$2)}'
awk '/SwapTotal/ {exit (!$2)}' /proc/meminfo

The last two commands are probably the most robust, the first two won't (as is) confirm the existence of swap when only swap files are used (somewhat unusual, but possibly found during an OS installation, or on diskless systems which swap over NFS).

You can use this instead to detect (or count, use -c instead of -q) swaps:

grep -qE "(partition|file)" /proc/swaps

(This will also count swap on /dev/nbd network block devices, swap block devices are counted as "partition" swap devices, at least up until linux-3.13.5.)

2

I'm not sure if every swap on every system always contains "/dev"... And/or if you wanted to know how many swaps are in use...

I think /proc/swaps should have an extra line for each swap that's in use, and if there's no swap then it's only one line (of titles). So wc -l should tell the number of lines and therefore the number of swaps - 1.

So this should give the number of swaps in use:

 swapnum=$(( $(cat /proc/swaps|wc -l) - 1 ))

(or if you really hate cat for some reason,)

 swapnum=$(( $(wc -l < /proc/swaps) - 1 ))

and can be tested if = 0 or whatnot

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .