launchd – Set environment variable for the whole GUI session (Aka without using `~/.zshenv`)

Spread the love

(EDIT OF 06/02/2023 : Previous title was
Variables set using launchctl setenv aren’t part of environment in Mac OS 12 )

I’m a daily Linux user and decided to try Mac recently.
I have a Macbook pro 13″ early 2015 that currently run macOS Monterey (12.6.3).

I’m struggling since a few day to setup SSH_AUTH_SOCK environment variable for my whole session

I relied on the following plist file in $HOME/Library/LaunchAgents/:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">




I then activate the agent using launchctl bootstrap gui/501/ (or something similar, i don’t remember well) and restart my session.

The binary mc-agent is running as expected but:

  • when i check SSH_AUTH_SOCK variable, it still contains the default value, not the one superseeded by my script.
  • when i run virt-manager (which make use of this variable) from the Launchpad, it obviously doesn’t have the correct value.
  • when i run launchctl getenv SSH_AUTH_SOCK the variable value is the one expected.

did i missed something ?


After the first answer, which is correct but doesn’t fullfill my needs, i noticed that my question wasn’t clear enought.

At the end, i want to mimic the behaviour of regular ssh-agent.
On raw MacOS installation, ssh-agent is launched using a plist file at GUI session launch, out of any shell.

I want my agent to be launched at GUI session startup and the environment variable set for the whole session, in or out the shell.

The goal is, when i launch virt-manager (which is a graphical app) directly from the finder or launchpad, no shell is spawned to launch it, virt-manager won’t inherit the variable set in my .zshenv or .bashrc, right ?
This is the same i guess for any IDE with git connectivity.

For example, in Linux, this would be achieved by tweaking Xsession for your favourite DM or by using legacy startup mode for xsession and setting a .xinitrd or .Xsession.
Then, every variable set this way will be inherit by any applications launched from the window manager as it’s part of its environment.

I have read this week end several methods to do this with launchctl/ launchd but it seems that all of them stopped working on later MacOS versions…

Author: Dhanraj7978

Leave a Reply

Your email address will not be published. Required fields are marked *