bash: automate mounting folders to home from other drive

94 views Asked by At

I would like to automatically mount my home folders from an external drive with just one script. My system is Ubuntu 16.04.

I would like to check if folders with the same name as folders in HOME exist in the external directory, then rename the folders in HOME to foldername_local and mount the external directories folder in HOME.

This is how far I got with the help of google and stackoverflow:

REMOTE=/path/to/remote/location

#create a list of external folders    
rLIST=$(find $REMOTE -maxdepth 1 -type d -name [^\.]\* -printf '%f\n'| sed 's:^\./::')

#create a list of folders in HOME
hLIST=$(find $HOME -maxdepth 1 -type d -name [^\.]\* -printf '%f\n'| sed 's:^\./::')

#declare comparison function
contains() {
[[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
} 

for item  in "$rLIST"; do 

 if contains hLIST item 
  then 
 #rename folder and mount external drive fodlers
 mv $HOME$item $HOME$item_local
 mount --bind $REMOTE$item $HOME$item
  else
 continue
fi

done

Creating the folder name lists works so far.

Unfortunately the comparison part does not work and I am stuck.

I appreciate any ideas on how to solve this.

sources:
How do I check if a variable exists in a list in BASH
Listing only directories in UNIX

1

There are 1 answers

4
Ipor Sircer On BEST ANSWER
for item in /path/to/remote/location/*; do 
     dir=${item##*/}
     [ -d $item ] && [ -d /home/$dir ] && mv /home/$dir /home/${dir}_local && mkdir /home/$dir && mount --bind $item /home/$dir
done