Give the mount point of a path

Posted by Charles Stewart on Stack Overflow See other posts from Stack Overflow or by Charles Stewart
Published on 2010-01-30T10:36:25Z Indexed on 2010/05/24 14:41 UTC
Read the original article Hit count: 208

Filed under:
|
|
|
|

The following, very non-robust shell code will give the mount point of $path:

 (for i in $(df|cut -c 63-99); do case $path in $i*) echo $i;; esac; done) | tail -n 1

Is there a better way to do this?

Postscript

This script is really awful, but has the redeeming quality that it Works On My Systems. Note that several mount points may be prefixes of $path.

Examples On a Linux system:

cas@txtproof:~$ path=/sys/block/hda1
cas@txtproof:~$ for i in $(df -a|cut -c 57-99); do case $path in $i*) echo $i;; esac; done| tail -1
/sys

On a Mac osx system

cas local$ path=/dev/fd/0
cas local$ for i in $(df -a|cut -c 63-99); do case $path in $i*) echo $i;; esac; done| tail -1
/dev

Note the need to vary cut's parameters, because of the way df's output differs: indeed, awk is better.

Answer It looks like munging tabular output is the only way within the shell, but

df /dev/fd/impossible  | tail -1 | awk '{ print $NF}'

is a big improvement on what I had. Note two differences in semantics: firstly, df $path insists that $path names an existing file, the script I had above doesn't care; secondly, there are no worries about dereferncing symlinks.

It's not difficult to write Python code to do the job.

© Stack Overflow or respective owner

Related posts about linux

Related posts about bash