1

I'm doing a simple test to see if I can run a shell script in nginx easily. Lua seems a good solution. So I added

content_by_lua_block {
   local myvar = "abcd"
   local file = io.popen("myshellscript.sh myvar")
   local result = file:read("*a")
   ngx.say(result)
}

in my nginx.conf. In myshellscript.sh, I use echo "#1" to print the value of the parameter. But instead of seeing "abcd", I see "myvar" from the output. So what's the proper way to pass a variable as a parameter to the shell script in nginx lua? I know os.execute("myshellscript.sh myvar") can do the similar job as popen, but I don't know how to get the output to the stdout or the exit code from the shell script.

Wqh
  • 75
  • 1
  • 10

1 Answers1

0

You need to substitute myvar with the value of your variable - otherwise you're passing the literal string myvar. Since abcd does not need to be quoted, simply concatenating myvar will work for this example:

local file = io.popen("myshellscript.sh " .. myvar)

or for a more robust solution that quotes strings using single quotes:

local function quote(param)
    return "'" .. param:gsub("'", [['\'']]) .. "'"
end
local file = io.popen("myshellscript.sh " .. quote(myvar))
Luatic
  • 8,513
  • 2
  • 13
  • 34