【问题标题】:Nginx: Execute shell script w/ arguments when specific file not foundNginx:找不到特定文件时执行带参数的shell脚本
【发布时间】:2020-08-31 06:00:03
【问题描述】:

我想在找不到特定文件时执行带参数的 shell 脚本 (404)。

作为起点,我使用了以下 sn-p:

location ~* ^/(?<bz2file>.+\.bz2)$ {
  log_by_lua_block {
    os.execute("/usr/local/bin/script")
  }
}

但我不知道,仅当文件不存在时如何运行。

正如我所读,os.execute 也不允许参数?

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    您可以尝试以只读方式打开文件,如果 io 对象不是 nil 并且存在,则表示您的文件存在。 (但一定要释放对象,否则你的文件将被 lua 持有直到应用程序运行)。

    os.execute 在 shell 中调用给定的命令,它自己的函数没有任何额外的参数。但是,您可以在您正在执行命令的单个字符串中传递命令行参数,它会完美地工作,就像使用终端应用程序执行命令一样。使用参数运行 os.execute 的示例是:

    os.execute("echo hello world")
    os.execute("command arg1 arg2 arg3")
    

    要在纯 Lua 中实现您的目标,无需任何额外的库,您可以使用以下代码:

    local f = io.open("/usr/local/bin/script", "r") -- Open our file read-only.
    -- Is the IO object valid?
    if f ~= nil then
        -- In case it exists, our file is valid, so we need to release it before we can execute it.
        io.close(f)
    
        -- Execute using our arguments.
        os.execute("/usr/local/bin/script arg1 arg2 arg3")
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2015-03-01
      相关资源
      最近更新 更多