luaenvironment-variablesuidgetenv

Lua os.getenv("UID") returns `nil` but environment variable it's already set


I'm writing a yazi plugin to preview documents. I'm on GNU/Linux. I'm trying to save the temporary files in a dedicated folder with the UID —user id— as suffix.

According to Programming in Lua

The os.getenv function gets the value of an environment variable. It receives the name of the variable and returns a string with its value.... If the variable is not defined, the call returns nil

The thing is, UID it's indeed defined

[user@hostname ~]$ echo $UID
1000

What I've tried is to use os.getenv("UID") but the function returns nil. On the other hand, other environment variables such as XDG_RUNTIME_DIR or HOME are retrieved successfully.

For instance

...

local user_id = os.getenv("UID")
local run_dir = os.getenv("XDG_RUNTIME_DIR")
local tmp_dir = run_dir .. "/office.yazi-" .. user_id .. "/"
local pdf_file = tmp_dir .. self.file.name:gsub("%..*$", ".pdf")

...

Fails to concatenate a nil value assigned to user_id due to os.getenv("UID")

Another approach I've tried is to use io.popen() instead

...

local handle = io.popen("id -u")
local user_id = handle:read("*a")
handle:close()
local run_dir = os.getenv("XDG_RUNTIME_DIR")
local tmp_dir = run_dir .. "/office.yazi-" .. user_id .. "/"
local pdf_file = tmp_dir .. self.file.name:gsub("%..*$", ".pdf")

...

But the problem with said approach is that returns a trailing newline character as

1000\n

And maybe I can remove it somehow, but as it's a plugin what I'm writing I would prefer to go down the os.getenv route and keep it simple as far it's possible. If what I'm asking it's not possible, please let me know.

My guess is os.getenv("UID") not reading the correct variable name or trying to read it from the wrong place.

Does someone has any idea as to why is this happening or any suggestion as to read the UID env?


Solution

  • $UID is not an environment variable, thus you cannot get it with os.getenv

    Your another approach can work, just change the mode to read one line:

    local handle = io.popen("id -u")
    local user_id = handle:read("l")
    handle:close()
    

    Or you can pass $UID to your lua script as an argument:

    $ lua example.lua $UID
    
    -- example.lua
    local user_id = arg[1];