How to test if a given path is a mount point

后端 未结 10 822
-上瘾入骨i
-上瘾入骨i 2021-01-31 08:41

Suppose do you want test if /mnt/disk is a mount point in a shell script. How do you do this?

相关标签:
10条回答
  • 2021-01-31 09:09
    mount | awk '$3 == "/pa/th" {print $1}'
    

    Empty if is not a mountpoint ^^

    0 讨论(0)
  • 2021-01-31 09:11

    Not relying on mount, /etc/mtab, /proc/mounts, etc.:

    if [ `stat -c%d "$dir"` != `stat -c%d "$dir/.."` ]; then
        echo "$dir is mounted"
    else
        echo "$dir is not mounted"
    fi
    

    When $dir is a mount point, it has a different device number than its parent directory.

    The benefit over the alternatives listed so far is that you don't have to parse anything, and it does the right thing if dir=/some//path/../with///extra/components.

    The downside is that it doesn't mark / as a mountpoint. Well, that's easy enough to special-case, but still.

    0 讨论(0)
  • 2021-01-31 09:15

    Using GNU find

    find <directory> -maxdepth 0 -printf "%D" 
    

    will give the device number of the directory. If it differs between the directory and its parent then you have a mount point.

    Add /. onto the directory name if you want symlinks to different filesystems to count as mountpoints (you'll always want it for the parent).

    Disadvantages: uses GNU find so less portable

    Advantages: Reports mount points not recorded in /etc/mtab.

    0 讨论(0)
  • 2021-01-31 09:20
    if mount | cut -d ' ' -f 3 | grep '^/mnt/disk$' > /dev/null ; then
       ...
    fi
    

    EDIT: Used Bombe's idea to use cut.

    0 讨论(0)
提交回复
热议问题