How to get mount point of filesystem containing given file
On GNU/Linux, if you have GNU stat
from coreutils 8.6 or above, you could do:
stat -c %m -- "$file"
Otherwise:
mount_point_of() {
f=$(readlink -e -- "$1") &&
until mountpoint -q -- "$f"; do
f=${f%/*}; f=${f:-/}
done &&
printf '%s\n' "$f"
}
Your approach is valid but assumes the mount point doesn't contain space, %, newline or other non-printable characters, you can simplify it slightly with newer versions of GNU df
(8.21 or above):
df --output=target FILE | tail -n +2
For Linux we have findmnt from util-linux exactly made for this
findmnt -n -o TARGET --target /path/to/FILE
Note that some kind of random mountpoint may be returned in case there are several bind mounts. Using df
has the same problem.
You could do something like
df -P FILE | awk 'NR==2{print $NF}'
or even
df -P FILE | awk 'END{print $NF}'
Since awk
splits on whitespace(s) by default, you don't need to specify the -F
and you also don't need to trim the whitespace with tr
. Finally, by specifying the line number of interest (NR==2
) you can also do away with tail
.