MacOS – Shell script to rsync or if not mounted – mount and rsync

backupcommand linemacosmount

This is what I've got so far:

!/bin/sh

Storage Folder Backup

Defines mount point

LOCALMOUNTPOINT="/Volumes/thisisanetworkshare"

Checks for mount

if mount | grep "on $LOCALMOUNTPOINT" > /dev/null; then

If already mounted initiates rsync job

caffeinate -i rsync -av /Users/auser/storage/ /Volumes/thisisanetworkshare/ --log-file=/Users/auser/rsync.log

Otherwise mounts and initiates rsync job

else
    mkdir thisisanetworkshare
    mount_smbfs //thisnetwork/thisisanetworkshare /Volumes/thisisanetworkshare
    caffeinate -i rsync -av /Users/auser/storage/
    /Volumes/thisisanetworkshare/ --log-file=/Users/auser/rsync.log
fi

So basically I want to start an rsync if the network share is already mounted but if it's not then I would like to mount that network share and start an rsync.

The network share requires auth but this is saved in the keychain so doesn't ask for it in finder. Does this matter for a shell script?

Thanks in advance!

Best Answer

Using the proper normal syntax of the command line version of the mount command from the command line or a bash script for a password protected SMB Share will require entering the password, by one means or another. However from a bash script or command line there is a way to access the stored Keychain password to mount the SMB Share without entering the password in the bash script or from the command line.

The following assumes both the authenticating User Name and Password for the target SMB Share is stored in the User's Keychain.

Since the authenticating User Name and Password for the target SMB Share is stored in the User's Keychain then mounting the target SMB Share can be done via AppleScript within the bash script or command line using the osascript command.

In the following example I shared the Temp folder on another system on my Network having the IP Address: 192.168.169.227

I first mounted this via Finder's Go menu > Connect to Server... where I checked the "Remember this password in my keychain" check box so it's stored in the Keychain. Once that was done I unmounted the share and used the following command to mount it from a bash script.

osascript -e 'tell application "Finder" to mount volume "smb://192.168.169.227/Temp"'

I did not need to pre-create the "/Volumes/Temp" folder as that is done automatically by this method unlike using the mount -t smbfs //... command normally where the mount point supplied has to already exist.

So as you write your bash script use this method in place of the normal command line version of the mount command.