How to test if a given path is a mount point

2019-03-08 18:26发布

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

标签: bash unix shell
10条回答
smile是对你的礼貌
2楼-- · 2019-03-08 19:01
for mountedPath in `mount | cut -d ' ' -f 3`; do
    if [ "${mountedPath}" == "${wantedPath}" ]; then
        exit 0
    fi
done
exit 1
查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-08 19:04
df $path_in_question | grep " $path_in_question$"

This will set $? upon completion.

查看更多
对你真心纯属浪费
4楼-- · 2019-03-08 19:11
if mount | cut -d ' ' -f 3 | grep '^/mnt/disk$' > /dev/null ; then
   ...
fi

EDIT: Used Bombe's idea to use cut.

查看更多
做自己的国王
5楼-- · 2019-03-08 19:12

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.

查看更多
登录 后发表回答