Bash array multi dimensional shell script for SSHFS mounting on Linux

Hello there folks!

I use the following to mount remote filesystems via a menu entry in jgmenu:

for u in $HOME/Remote/SSHFS/*
do
  if [ -d $u ]; then
    basename "$u" >/dev/null
	acct="$(basename -- $u)"
	
	IFS=- read -r left right <<< "$acct"
	if mountpoint "${HOME}/Remote/SSHFS/${acct}" >/dev/null; then
		printf '%b\n' "unmount ${right},fusermount -u /home/schwim/Remote/${right}"
	else
		printf '%b\n' "mount ${right},sshfs -o workaround=rename $left@$right:/home/$left /home/schwim/Remote/SSHFS/${acct}"
	fi

  fi
done

Which, for a while, worked swimmingly but as I gained more remote filesystems to mount, began to fail due to differing remote file paths and changing enviromental variables.

So I’d like to create an array that I loop through to build these menu entries. Each array entry needs to contain:

Site1:
host: domain.com
user: schwim
local dir: /home/schwim/domain.com
remote dir: /var/www/client1
Site2:
host: anotherdomain.com
user: bob
local dir: /home/schwim/anotherdomain.com
remote dir: /home/bob/public_html
More sites here

I’m failing at making an array for this, however. I’ve only ever worked with arrays in scripting languages like php and I just can’t figure out how to do it in a bash script.

Any help in making this array and figuring out how to loop through it would be greatly appreciated.

Thanks for your time!

Welcome @Schwim to nixCraft forum.

Instead of bash array try something as follows which is easy too:

Create a text file

Say input.txt seprated by , as IFS (input field separator)

domain.com,schwim,/home/schwim/domain.com,/var/www/client1
anotherdomain.com,bob,/home/schwim/anotherdomain.com,/home/bob/public_html

Bash while loop to read text file line-by-line

We can read those using a simple bash while loop:

db="input.txt"

while IFS=, read -r domain user ldir rdir
do
	echo "$domain $user $ldir $rdir"
done <"$db"

Now you can build your logic easily. Let us know if you need any more help.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki