Understanding the scripting environment

If you have a script that works in the Terminal but not Alfred, chances are it's due to a different environment: a Unix concept whose modern form has been a part of computing since the late 70's. You can read about in on Wikipedia but the gist is they are values that affect how processes run on your machine.

When you open a Terminal, it launches a shell (the Z shell by default on macOS) which loads a set of configuration files containing default values and - more importantly - your custom settings. The latter are bound to be the cause of the different behaviour you're seeing between Alfred and the Terminal.

The most likely culprit with be PATH, which defines where tools check for executables. It's what allows you to run ls instead of /bin/ls. It starts out short and expands as you set up your system. For example, to use Homebrew you configure your PATH to include /opt/homebrew/bin or /usr/local/bin.

By design, Alfred does not see this custom environment. Its PATH is /usr/bin:/bin:/usr/sbin:/sbin and isn't affected by your shell's configuration files.

Making your Workflow mostly independent of external changes benefits you both as a Workflow developer and a Workflow user: by ensuring everyone has a similar starting point, changing this environment must be a conscious decision with clear consequences. When you do want to make that choice, the best method is the one that changes the least about the environment:

  • Method 1: Use the full path to your tool. Instead of php, call /usr/local/bin/php. Simplest method, but not appropriate for a Workflow to share with random users.
  • Method 2: source your shell's configuration file before calling your script. Example: source "${HOME}/.zshrc". Even less suitable for sharing, but may be necessary if your needs are specific. This will make your script slower.
  • Method 3: Set PATH before calling your tools. For Homebrew binaries, use /opt/homebrew/bin:/usr/local/bin:${PATH}. Remember to inform your users of what tools they will need to install.

Latest Blog Post:

Alfred 5 Early Access is Now Available!

CacheFly Campaign Monitor

"Alfred" is a registered trademark of Running with Crayons Ltd. ©2022 Running with Crayons Ltd. All rights reserved.

Terms & Conditions, Privacy Policy, Cookies.