Launching a macOS application with a custom path
2019-07-23

Sometimes you need an application that you launch from the Dock or Launchpad — anywhere other than the terminal — to run with a custom path.

Normally, applications start with an extremely limited path: /usr/bin:/bin:/usr/sbin:/sbin.

But if you are running an editor or an IDE like WebStorm or Visual Studio Code, it might need to use various executables (compilers, linters etc.) which have to be on the path but are installed elsewhere, like somewhere in your home directory.

In particular, I have this issue with running Elm-related commands like elm (the compiler), elm-format, elm-test and so on in Visual Studio Code. The Elm extension in theory allows me to specify paths to these, but in practice it doesn’t work.

The “official” workaround is to add Visual Studio Code executable to the path, and then always start it from the terminal by running code. This is because in a shell, there are many ways to control the PATH environment variable.

But not so for applications started any other way. I tried everything I could find:

  • adding paths to /etc/paths and etc/paths.d (this only applies to the shell)
  • creating /etc/launchd.conf with appropriate commands (doesn’t work)
  • setting the path with launchctl setenv PATH <path> in my ~/.zshrc (doesn’t work)
  • creating ~/Library/LaunchAgents/startup.plist to run this command (doesn’t work)
  • running launchctl config system path <path> (doesn’t work).

Side note: you can examine the environment variables of a running process with this command:

ps eww -o command <pid>  | tr ' ' '\n'

So finally, I came up with a hybrid approach. I noticed that macOS Automator can create an application, and in the workflow, I can run a shell script. So this should give me the ability to control the path, and also have an icon sitting in the Dock (although all this effort wasn’t for the purposes of putting an icon in the Dock; I’m trying to open projects in VSCode using an application called Workspaces).

This actually works!

Create a launcher application in Automator

  • Start a new automation in Automator
  • Find “Run Shell Script” in the list of actions and add it to the workflow
  • Change “Pass Input” setting from “to stdin” to “as arguments”
  • Add the command; I use zsh so for me it’s:
source /Users/alex/.zshrc && code $1

(when Workspaces launches this application, it passes a directory for VS Code to open as the argument; this is what $1 is)

  • Save this workflow as an application
  • You can even change the icon to the VSCode icon using these instructions.

It appears that another option for creating a launcher would be Platypus, which allows you to create applications from scripts. However, I haven’t tried it.