MacOS – Shell set environment variables for command

command lineenvironment-variablesmacos

I want to run a program in Terminal and set its environment variables. According to my research one can do this using:

VARIABLE="value" VARIABLE2="value2" run_program

Now I'd like to set a variety of variables using a configuration file. Indeed, I could inject variables into the active shell using:

. program_variables.config

I then can use echo $VARIABLE in the terminal.

Anyway, when I now run

. program_variables.config run_program

I cannot access the variables within the program. I also tried separating the two parts with ; and &&.

After thinking about what's happening there I had the following ideas:

cat program_variables.config | xargs run_program
cat program_variables.config | tr -d '\n' run_program

and a few more.

I didn't write the called program myself so I cannot change the behavior how variables are read.

Any ideas how I output the file as if I would have written its content in the shell myself?

Best Answer

The variables are set only in the current scope, to make them visible in a program that is called or after a source (e.g. . file) you need to export them.

Thus program_variables.config should be

export VARIABLE="value" 
export VARIABLE2="value2"

Then just run the executable,

This can all be in one script to run the executable

#!/bin/sh
export VARIABLE="value" 
export VARIABLE2="value2"
run_program

Save this file and make it executable.
Then just use the name os this file as the program