Recursively Remove Mount Points

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

Recursively Remove Mount Points

Post by s243a »

I wrote a script to recursively remove mount points based on code from my previous post:
"Get the Original Mount Point (i.e. exclude binds)"

Currently the input is hard coded (e.g. "PATTERN=('^/mnt/cont')" but it wouldn't be hard to modify it to accept input arguments:

Code: Select all

#!/bin/bash
PATTERN=('^/mnt/cont') #Make this an array so that you can specify extra grep options. 
REMOVE=true
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
}'
TEMP="$(mktemp -p /tmp fndmnt_XXXX)"
findmnt -o TARGET,SOURCE -D -n | grep ${PATTERN[@]} | awk "$awk_fn" | sort -t '|' -r -k1 | cut -d'|' -f2 | tee "$TEMP"
while read a_mnt_pt; do
   umount -l "$a_mnt_pt"
   sleep 2
   if [ ! "$(ls -A "$a_mnt_pt")" ] && [ "$REMOVE" = true ]; then
     rmdir "$a_mnt_pt"
   fi
done <"$TEMP"

One might want to incorporate this as a feature in puppy where you can right-click on a folder and recursively remove all mount points.

Post Reply

Return to “Scripts”