Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the mountpoint a file resides on?

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:

/media/my_mountpoint

How can I do this? Preferably in Python and without using external libraries / tools. (Both are not a requirement.)

like image 537
Georg Schölly Avatar asked Dec 15 '10 18:12

Georg Schölly


People also ask

How do I check my Mountpoint?

Use the lsfs command to display information about mount points, permissions, file system size and so on. Important: For file systems to be NFS exported, be sure to verify that logical volume names for these file systems are consistent throughout the cluster.

Where is the Mountpoint of a directory in Linux?

The findmnt command is a simple command-line utility used to display a list of currently mounted file systems or search for a file system in /etc/fstab, /etc/mtab or /proc/self/mountinfo.

How do I find my mount list?

The command findmnt lists all mount points. To do this the findmnt reads files /etc/fstab, /etc/fstab. d, /etc/mtab or /proc/self/mountinfo. To run it, simply just the command below.

How do you check if FS is mounted?

To see the list of mounted filesystems, type the simple “findmnt” command in the shell as below, which will list all the filesystems in a tree-type format. This snapshot contains all the necessary details about the filesystem; its type, source, and many more.


2 Answers

You may either call the mount command and parse its output to find the longest common prefix with your path, or use the stat system call to get the device a file resides on and go up the tree until you get to a different device.

In Python, stat may be used as follows (untested and may have to be extended to handle symlinks and exotic stuff like union mounts):

def find_mount_point(path):
    path = os.path.abspath(path)
    orig_dev = os.stat(path).st_dev

    while path != '/':
        dir = os.path.dirname(path)
        if os.stat(dir).st_dev != orig_dev:
            # we crossed the device border
            break
        path = dir
    return path

Edit: I didn't know about os.path.ismount until just now. This simplifies things greatly.

def find_mount_point(path):
    path = os.path.abspath(path)
    while not os.path.ismount(path):
        path = os.path.dirname(path)
    return path
like image 160
Fred Foo Avatar answered Nov 16 '22 23:11

Fred Foo


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.

like image 22
camh Avatar answered Nov 16 '22 21:11

camh