just icon indicating copy to clipboard operation
just copied to clipboard

env() does not see exported variables in the same Justfile

Open NiceGuyIT opened this issue 8 months ago • 1 comments

From the docs:

  • env(key, default) — Retrieves the environment variable with name key, aborting if it is not present. (link)
  • Assignments prefixed with the export keyword will be exported to recipes as environment variables (link)

Using the above logic, it seems the following will work.

export ENV_VAR := "Hello World from ENV_VAR!"
export ENV_VAR_SHELL := `uname -m`

VAR := "Hello World from VAR!"
VAR_SHELL := `uname -o`

# Test the environment variables.
@test-env-var $PARAM_VAR="Hello World from PARAM_VAR!":
	echo "env(ENV_VAR): '{{ env("ENV_VAR", "not set") }}'"
	echo "\$ENV_VAR: '${ENV_VAR}'"
	echo "{ {ENV_VAR} }: '{{ ENV_VAR }}'"
	echo ""
	echo "env(PARAM_VAR): '{{ env("PARAM_VAR", "not set") }}'"
	echo "\$PARAM_VAR: '${PARAM_VAR}'"
	echo "{ {PARAM_VAR} }: '{{ PARAM_VAR }}'"
	echo ""
	echo "env(ENV_VAR_SHELL): '{{ env("ENV_VAR_SHELL", "not set") }}'"
	echo "\$ENV_VAR_SHELL: '${ENV_VAR_SHELL}'"
	echo "{ {ENV_VAR_SHELL} }: '{{ ENV_VAR_SHELL }}'"

The result is that env("ENV_VAR") does not see the variable exported in the Justfile.

env(ENV_VAR): 'not set'
$ENV_VAR: 'Hello World from ENV_VAR!'
{ {ENV_VAR} }: 'Hello World from ENV_VAR!'

env(PARAM_VAR): 'not set'
$PARAM_VAR: 'Hello World from PARAM_VAR!'
{ {PARAM_VAR} }: 'Hello World from PARAM_VAR!'

env(ENV_VAR_SHELL): 'not set'
$ENV_VAR_SHELL: 'x86_64'
{ {ENV_VAR_SHELL} }: 'x86_64'

The docs DO state Exported variables and parameters are not exported to backticks in the same scope. In the example above, setting the environment variable is in the global (script?) scope while env() is in the recipe scope. Is the same Justfile considered the same scope?

NiceGuyIT avatar Apr 19 '25 21:04 NiceGuyIT

The issue appears to be that std::env doesn't have access to the environment variables that have been added. They are present in the context in Just. I have a little fix that would produce this functionality (so env() would produce the values as you would like), I'm just not sure if it's the desired usage from Justs point of view.

Hwatwasthat avatar Apr 23 '25 14:04 Hwatwasthat

I can definitely see the argument for this, although it is a change in behavior, and possibly a breaking one for existing justfiles.

casey avatar Jun 24 '25 08:06 casey