How to mount a samba NAS from the commandline in OSX

Posted on November 1, 2018
Tags: howto, bash, osx, emacs

A commandline oneliner to mount a network drive in OSX using Finder from applescript. (+ script & emacs lisp function)

At work we use a Network Access Server (NAS) to store data and my office computer is an iMac (… yeah, I know). Somehow I never managed to use the normal mount command to connect to the server. Of course, one can always use the Finder GUI to connect to the NAS (“CMD+K”), but as I recently needed to use my office computer remotely and access data from the NAS, a mount method from the terminal was needed.

After some searching I found a solution using applescript (https://stackoverflow.com/questions/4108808/applescript-oneliner). One can basically write a script that tells Finder to mount the NAS without the GUI,

# mount_nas.scpt
tell application "Finder"
  activate
  open location "smb://<user>@<host>/<path>"
end tell

which can then be envoked by

osascript mount_nas.scpt

I also wanted a direct oneliner, which can be achieved by

osascript -e "tell application \"Finder\" to activate & open location \"smb://<user>@<host>/<path>\"" &> /dev/null

Somehow this threw an ugly warning, which I just suppressed by appending '&> /dev/null'.

Finally I wanted to mount the NAS from within emacs, which got me to this function:

(defun mnd/mount-nas ()
  "mount a samba nas in osx using finder from applescript"
  (interactive)
  (call-process-shell-command
   (concat "osascript -e "
           "\"tell application \\\"Finder\\\" to activate & "
           "open location "
           "\\\"<user>@<host>/<path>\\\"\" "
           "&> /dev/null")))

Just needed to be a bit careful with the escapes.