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.)
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With