command line – Script menu: how to reference user-path utilities (PATH / environment is missing)

Summary

How can I execute scripts from the system-wide Script menu with a normal environment? It seems the environment is not being setup at all.

Scripts that are run from the script menu can find and execute commands from the base system. However, user-installed utilities are not found on the path. Also, /usr/bin/env foo is not finding commands that are installed outside of the base system.

Background

The system Script menu appears at the right side of the menu bar. It is enabled via Script Editor.app > Preferences > Show Script menu in menu bar. It displays scripts located in ~/Library/Scripts and other system locations. The menu can execute AppleScript, JXA, bash, python and other scripts (use shebang as needed).

enter image description here

Investigation So Far

Scripts that are run from the Script menu don’t inherit the user’s bash environment. They know the shell is BASH and your USER name, but no initialization occurs. I ran a little script to dump the env to a text file

~/Library/Scripts/dump_env.sh (be sure to make executable):

#!/bin/bash
env > ~/env.txt

Here are the interesting entries.

USER=mat
LOGNAME=mat
SHELL=/bin/bash
PATH=/usr/bin:/bin:/usr/sbin:/sbin
PWD=/
HOME=/Users/mat
_=/usr/bin/env

It is very vanilla. None of the custom paths are included. For example, the following are unavailable:

/usr/local/bin/svn # Subversion source control client
/opt/local/bin/python3 # python3 installed via MacPorts
~/bin

The latter two are normally sourced in my .bash_profile. /usr/local/bin/ is setup by path_helper which is called by /etc/profile (though apparently not for the Script menu).

I’m running macOS 10.13 High Sierra, but I’m interested whether others are getting different results.

Ideal Solution

  1. Avoid hard-coding path to executables in shebang. Ex: if I install a different python version / distribution, I want to use it in all my scripts. /usr/bin/env python3 accomplishes this, but it seems to depend on the PATH?
  2. Finds utilities in /usr/local/bin
  3. Specify PATH once for CLI and Script menu (and GUI?). If I install a new Python I would like it to be used everywhere.
  4. Specify PATH only for user-level processes. I don’t want system processes using binaries from in my add-on path entries (especially user-permissioned path entries).
  5. Avoid breaking 3rd party builds/installers/programs that were written with assumptions about what is present on my macOS install.

I’m looking into launchctl, which can be used to setup environment for GUI apps. Not sure if it still works or if it will work with the Script menu.