Print a list of ALL environment variables

I would like to print a list of all environment variables and their values. I searched Stackoverflow and the following questions came close but did not answer me:

Unlike C, Lua does not have an envp** parameter, which is passed to main() , so I could not find a way to get a list of all the environment variables. Does anyone know how I can get a list of the name and values โ€‹โ€‹of all environment variables ?

+7
source share
4 answers

This code was extracted from the old POSIX binding.

 static int Pgetenv(lua_State *L) /** getenv([name]) */ { if (lua_isnone(L, 1)) { extern char **environ; char **e; if (*environ==NULL) lua_pushnil(L); else lua_newtable(L); for (e=environ; *e!=NULL; e++) { char *s=*e; char *eq=strchr(s, '='); if (eq==NULL) /* will this ever happen? */ { lua_pushstring(L,s); lua_pushboolean(L,0); } else { lua_pushlstring(L,s,eq-s); lua_pushstring(L,eq+1); } lua_settable(L,-3); } } else lua_pushstring(L, getenv(luaL_checkstring(L, 1))); return 1; } 
+2
source

Lua's standard functions are based on C-standard functions, and there is no C-standard function to get all environment variables. Therefore, the standard Lua function does not exist.

You will need to use a module like luaex , which provides this functionality.

+5
source

You can install the lua-posix module. Alternatively, RedHat installations have built-in POSIX routines, but you must do the trick to enable them:

  cd /usr/lib64/lua/5.1/ # (replace 5.1 with your version) ln -s ../../librpmio.so.1 posix.so # (replace the "1" as needed) lua -lposix > for i, s in pairs(posix.getenv()) do print(i,s,"\n") end 

The trick is to create a soft link in the io RPM directory and to name the soft link the same library name that LUA will try to open. If you do not, you will receive:

 ./librpmio.so: undefined symbol: luaopen_librpmio 

or similar.

+1
source
 local osEnv = {} for line in io.popen("set"):lines() do envName = line:match("^[^=]+") osEnv[envName] = os.getenv(envName) end 

in some cases this will not work, for example, "no valid shell for the user running your application"

0
source

All Articles