Get the Original Mount Point (i.e. exclude binds)

interpretive language scripts


Moderator: Forum moderators

Post Reply
s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Get the Original Mount Point (i.e. exclude binds)

Post by s243a »

The findmnt function is useful for printing the mountpoints in an easy to process format. We might look for the mount point of an sfs file by first finding which loop device that it is mounted on:

Code: Select all

loop=$(losetup -a | grep  "$SFS_PATH"  | sed "s/:.*$//" )

However, if more than one folder is boundd to the mount point then this when we try to find the mount point using either /proc/mounts or findmnt we will see more than one entry that matches the loop device. That said the findmnt function is still useful to get simplified output. For isntance we can get the mount point followed by the loop device with the following command, "findmnt -o TARGET,SOURCE -D -n" and if we specificicly wanted say mount points associated with loop5 and no subpaths then we would do the follwoing:

Code: Select all

findmnt -o TARGET,SOURCE -D -n | grep 'loop5$' 

To get a single output we observe that the first field of "/proc/self/mountinfo" is the mount id (see docs). Since ids are usually sequantial the assumption is that the entry with the lowest value of "mount id" is the orginal mount.

So what we do is we write an awk function that appends the mount id to the above output:

Code: Select all

awk_fn='
function get_mnt_id(mnt_pt,loop){
  if (length(mnt_pt) > 0 && length(loop)>0){ 
    cmd="cat /proc/self/mountinfo | sort | grep '" loop "' | grep " mnt_pt " | head -n 1" 
  } else if (length(mnt_pt) > 0){
    cmd="cat /proc/self/mountinfo | sort | grep '" mnt_pt "' | head -n 1" 
  } else if (length(loop)>0){
    cmd="cat /proc/self/mountinfo | sort | grep '" loop "' | head -n 1" 
  }
  while ((cmd | getline )){
    mnt_id=$1
    break  
  }
  close(cmd)
  return mnt_id
}
{
  mnt_pt=$1
  loop=$2
  mnt_id=get_mnt_id(mnt_pt,loop) 
  print mnt_id "|" mnt_pt "|" loop
}'

and then we sort the output and take the first value to get the original mount point:

Code: Select all

findmnt -o TARGET,SOURCE -D -n | grep 'loop5$' | awk "$awk_fn" | sort -t '|' -k1 | cut -d'|' -f2 | head -n 1

P.S. the following thread was helpful in helping me to figure out how to do this:
https://unix.stackexchange.com/question ... ind-mounts

Post Reply

Return to “Scripts”