How to find the mountpoint a file resides on?

后端 未结 8 1755
半阙折子戏
半阙折子戏 2020-12-03 17:16

For example, I\'ve got a file with the following path:

/media/my_mountpoint/path/to/file.txt

I\'ve got the whole path and want to get:

8条回答
  •  被撕碎了的回忆
    2020-12-03 18:03

    My python is rusty, however you can use something like this with perl :

    export PATH_TO_LOOK_FOR="/media/path";
    perl -ne '@p = split /\s+/; print "$p[1]\n" if "'$PATH_TO_LOOK_FOR'" =~ m@^$p[1]/@' < /proc/mounts
    

    notice the " ' ' " around $PATH_TO_LOOK_FOR otherwise it won't work.

    //edit : python solution :

    def find_mountpoint(path):
        for l in open("/proc/mounts", "r"):
            mp = l.split(" ")[1]
            if(mp != "/" and path.find(mp)==0): return mp
    
        return None
    

提交回复
热议问题