hackbyte icon

ismounted.sh_2019-04-24T21-18-56CEST

hackbyte | PRO | 04/18/19 08:42:09 PM UTC | 0 ⭐ | 699 👁️ | Never ⏰ | []
Bash |

1.98 KB

|

None

|

0 👍

/

0 👎

#!/bin/bash
 
# function ismounted("PATH")
#
# checks if a given PATH is actually a mount..
#
# v2019-04-24T21-18-56CEST (UTC+2)
#   Added some bits of documentation and links for 
#   more in depth info. ;)
#
 
function ismounted() {
    # this funtion performs the actual test
    # if a path given as parameter is actually a mount.
    #
    # it uses default sh/bash return codes, according to this hint:
    # https://stackoverflow.com/questions/5431909/returning-a-boolean-from-a-bash-function/43840545#43840545
    #
    # Which means, on success, return 0,
    # on a failure (is not a mount) return anything else.
    #
    # the cut and grep below, just grab the mounted dirs from
    # /proc/self/mounts (delimeter is space and we want field number 2)
    # and then filters them (with exact match) against our parameter.
    #
    # After that, we can simply compare the trings we got.
    # It will be empty if no mount is found or it will exactly
    # be the path we got as parameter...
    #
    # http://tldp.org/LDP/abs/html/comparison-ops.html
    #
    if ! [ -d "$1" ] ; then
        # if our parameter is not a directory at all,
        # it usually can not be a mount... ;)
        return 1
    fi
    if [ "$(cut -d' ' -f2 /proc/self/mounts | grep -x "$1")" = "$1" ] ; then
        # our parameter matches against a existing mount,
        # just return with a exit status of 0
        return 0
    else
        # our parameter got no match,
        # so we return with a exit status of 1
        return 1
    fi
}
 
 
#
# this variant just uses the exitstatus to see if
# the dir is a mount.
#
if ismounted $1 ; then
    echo "$1 is mounted!"
else
    echo "$1 is not mounted!"
fi
 
#
# this variant calls ismounted and _inverts_ the returned exitstatus
# to get the stuff convenient for our test-case ( i need to know if mounts are _NOT_ existing)
#
if ! ismounted $1 ; then
    echo "$1 is not mounted!"
else
    echo "$1 is mounted!"
fi

Comments