How to find the mountpoint a file resides on?

后端 未结 8 1682
半阙折子戏
半阙折子戏 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
    
    0 讨论(0)
  • 2020-12-03 18:08

    Since python is not a requirement:

    df "$filename" | awk 'NR==1 {next} {print $6; exit}'
    

    The NR==1 {next} is to skip the header line that df outputs. $6 is the mount point. exit is to make sure we output only one line.

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