Charles Stewart Charles Stewart - 3 months ago 5x
Bash Question

Give the mount point of a path

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


(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 in shell?


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

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

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

Note the need to vary cut's parameters, because of the way df's output differs; using awk solves this, but even awk is non-portable, given the range of result formatting various implementations of df return.

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

df -P "$path" | tail -1 | awk '{ print $NF}'

based on ghostdog74's answer, is a big improvement on what I had. Note two new issues: firstly,
df $path
insists that
names an existing file, the script I had above doesn't care; secondly, there are no worries about dereferencing symlinks. This doesn't work if you have mount points with spaces in them, which occurs if one has removable media with spaces in their volume names.

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


df takes the path as parameter, so something like this should be fairly robust;

df "$path" | tail -1 | awk '{ print $6 }'