Setting Environment Variables in GUI Emacs

I use Emacs for most of my development work. When I’m not SSHed into a remote machine I generally stick with the GUI Emacs. On OS X this has the downside of not inheriting environment variables from your shell.

I could work around this by using setenv, but that would require me to duplicate the values of those variables. Thankfully there is a better solution:

(defun set-exec-path-from-shell-PATH ()
  (let ((path-from-shell (shell-command-to-string "$SHELL -i -c 'echo $PATH'")))
    (setenv "PATH" path-from-shell)
    (setq exec-path (split-string path-from-shell path-separator))))

This will invoke the shell to get the value of $PATH and then use setenv to set it. Then all you need to do is add (if window-system (set-exec-path-from-shell-PATH)) to your Emacs configuration.

There is nothing special about $PATH in this regard. You could easily extend this function to set other environment variables as needed.

I originally found this code on the Clojure mailing list.