2
votes

I am new to lua script features. I tried using,

  1. os.execute("export MY_VAR=10")
  2. io.popen("export MY_VAR=10")

from lua script.

I try reading MY_VAR variable from shell using echo $MY_VAR after lua script is executed but I do not see MY_VAR getting set to 10.

How do we set the environment variable using lua script?

1
One workaround you can do is to have the Lua code output the contents of a Bash script and then have bash "source" or "eval" that script. - hugomg

1 Answers

6
votes

Your problem isn't a lua problem. Your problem is misunderstanding how process environments work.

Every time you run os.execute or io.popen you are running a new process with new environment.

So while you may be correctly setting MY_VAR in that processes environment (and it would affect any processes run as children processes of that process) it doesn't survive beyond the death of the launched process and so cannot be seen by any other processes.

If you want to affect the lua process's environment (which would then, in turn, affect the environment's of processes run by lua) then you need a binding to the setenv system function (which lua itself doesn't provide as it doesn't pass the clean C test that lua uses for things it includes).