Skip to content

Instantly share code, notes, and snippets.

@VonHeikemen
Created September 29, 2024 01:01
Show Gist options
  • Save VonHeikemen/6b88ce596ac02b3ee5a7ddbaabebff3c to your computer and use it in GitHub Desktop.
Save VonHeikemen/6b88ce596ac02b3ee5a7ddbaabebff3c to your computer and use it in GitHub Desktop.
Template for (small) command line scripts written in lua (5.2)
#! /usr/bin/env lua
local function main(argv)
local name = argv[1] or 'World'
sh.spawn('echo "Hello, %s!"', name)
end
---
-- I/O helper functions
---
_G.sh = {}
function sh.q(str)
if str == nil then
return
end
return string.gsub(str, "'", [['"'"']])
end
function sh.qt(str)
if str == nil then
return
end
return sh.q(str:sub(1, #str - 1))
end
function sh.trim(str)
return str:match('^%s*(.*%S)') or ''
end
function sh.run(cmd, ...)
local command = cmd:format(...)
local p = io.popen(command, 'r') or {}
local output = p:read('*a')
local _, _, status = p:close()
if status ~= 0 then
error(string.format("Failed to execute '%s'", command))
return
end
return output
end
function sh.get(...)
return sh.qt(sh.run(...))
end
function sh.spawn(cmd, ...)
os.execute(cmd:format(...))
end
function sh.read(msg, ...)
io.write(msg:format(...))
return io.read()
end
function sh.confirm(cmd)
local input = sh.read('%s\nConfirm (y/n): ', cmd)
if input == 'y' then
sh.spawn(cmd)
end
end
main(_G.arg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment