如何测试给定路径是否为挂载点

时间:2009-01-26 09:33:52

标签: bash unix shell

假设你想要测试/ mnt / disk是否是shell脚本中的挂载点。 你是怎么做到的?

10 个答案:

答案 0 :(得分:52)

我发现在我的Fedora 7上有一个mountpoint命令。

来自man mountpoint:

NAME
       mountpoint - see if a directory is a mountpoint

SYNOPSIS
       /bin/mountpoint [-q] [-d] /path/to/directory
       /bin/mountpoint -x /dev/device

显然它带有sysvinit包,我不知道这个命令是否在其他系统上可用。

[root@myhost~]# rpm -qf $(which mountpoint)
sysvinit-2.86-17

答案 1 :(得分:20)

不依赖于mount/etc/mtab/proc/mounts等:

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

$dir是挂载点时,它的设备编号与其父目录不同。

到目前为止列出的替代方案的好处是你不必解析任何东西,如果dir=/some//path/../with///extra/components它做对了。

缺点是它没有将/标记为挂载点。嗯,这对特殊情况来说很容易,但仍然如此。

答案 2 :(得分:4)

使用GNU find

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

将给出目录的设备号。如果它不同 目录及其父目录,然后你有一个挂载点。

添加/。如果要将符号链接到不同的文件系统,请转到目录名称 算作挂载点(你总是希望它为父节点)。

缺点:使用GNU查找不那么便携

优点:报告挂载点未记录在/ etc / mtab中。

答案 3 :(得分:3)

if mount | cut -d ' ' -f 3 | grep '^/mnt/disk$' > /dev/null ; then
   ...
fi

编辑:使用Bombe的想法来使用剪切。

答案 4 :(得分:3)

df $path_in_question | grep " $path_in_question$"

这将在完成时设置$?

答案 5 :(得分:3)

不幸的是,如果您使用自动挂载,则mountpoint和stat将具有 MOUNTING 您正在测试的目录的副作用。或者至少它在Debian上使用自动cifs到WD MyBookLive网络磁盘。 我最终得到了/ proc / mounts的变体变得更复杂,因为每个 POTENTIAL 挂载已经在/ proc / mounts中,即使它实际上没有挂载!

cut -d ' ' -f 1 < /proc/mounts | grep -q '^//disk/Public$' && umount /tmp/cifs/disk/Public
Where
   'disk' is the name of the server (networked disk) in /etc/hosts.
   '//disk/Public' is the cifs share name
   '/tmp/cifs' is where my automounts go (I have /tmp as RAM disk and / is read-only)
   '/tmp/cifs/disk' is a normal directory created when the server (called 'disk') is live.
   '/tmp/cifs/disk/Public' is the mount point for my 'Public' share.

答案 6 :(得分:2)

for mountedPath in `mount | cut -d ' ' -f 3`; do
    if [ "${mountedPath}" == "${wantedPath}" ]; then
        exit 0
    fi
done
exit 1

答案 7 :(得分:0)

这是一个带有“df -P”的变体,它应该是可移植的:

mat@owiowi:/tmp$ f(){ df -P  | awk '{ if($6 == "'$1'")print   }' ; }
mat@owiowi:/tmp$ f /
/dev/mapper/lvm0-vol1  20642428  17141492   2452360      88% /
mat@owiowi:/tmp$ f /mnt
mat@owiowi:/tmp$ f /mnt/media
/dev/mapper/lvm0-media  41954040  34509868   7444172      83% /mnt/media

答案 8 :(得分:0)

mount | awk '$3 == "/pa/th" {print $1}'

如果不是挂载点,则为空^^

答案 9 :(得分:0)

stat --printf&#39;%m&#39; 显示给定文件或目录的安装点。

realpath 将相对路径转换为直接路径。

比较两者的结果将告诉您目录是否为挂载点。 stat 非常便携。 realpath 不那么重要,但只有在你想检查相对路径时才需要它。

我不确定 mountpoint 是多么便携。

if [ "$(stat --printf '%m' "${DIR}")" = "$(realpath "${DIR}")" ]; then
    echo "This directory is a mount point."
else
    echo "This is not a mount point."
fi

没有 realpath

if [  "${DIR}" = "$(stat --printf '%m' "${DIR}")" ]; then
    echo "This directory is a mount point."
else
    echo "This is not a mount point."
fi
相关问题