Terminal does not receive Environment Variables

We have been trying to understand why the Mac OS Terminal, when invoked with open, does not pass along the environment variables.

How to reproduce?

Create a new file /tmp/example.sh

#!/bin/sh
echo "SAMPLE_ENV='$SAMPLE_ENV'"
SAMPLE_ENV=123 open -a Terminal /tmp/example.command

Only prints: SAMPLE_ENV=''

Even when using

SAMPLE_ENV=123 open --env SAMPLE_ENV=1234 -a Terminal /tmp/example.sh   

it will only print SAMPLE_ENV=''

We know for sure that this was working several years ago. Why was the feature removed or is this a bug?

Any workaround?

Is there a workaround on how to launch a script in a new Terminal Window while passing the environment variables correctly?

Related

https://stackoverflow.com/questions/69768133/react-native-envs-are-undefined-in-metro-bundlers-config-file-when-bundling/73036234

As documented in the open man page, open does pass along environment variables:

Opened applications inherit environment variables just as if you had launched the application directly through its full path.

This isn’t working for you because Terminal is already running. By default open will reuse the existing instance of Terminal and there’s no way for open to set environment variables in already-running processes.

To see this work as you expect, start a second instance of Terminal by passing in the -n flag. However, that’s probably not what you want to do in your real setup because users get confused if multiple instances of Terminal are open (I got confused just testing this! :-).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Interesting how this works!

Indeed, it's super confusing to have multiple Terminal instances open. However, if the second instance of the Terminal could close itself after all tabs are closed, it would be a perfect fit for React Native's use case.

For example, an argument for Terminal that triggers:

-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSapplication*)sender
{
  return gQuitIfNoWindowLeft ? YES : NO;
}
Terminal.app --quit-automatically

or something.

By the way, thank you so much for every answer you give. Your help is always appreciated, eskimo.

Terminal does not receive Environment Variables
 
 
Q