lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, 2008-09-13 at 19:20 -0400, Norman Ramsey wrote:
...
> Here are some of the key pieces that make lua standalone a great
> replacement for shell scripts:
> 
>   lhf's posix library
> 
>   A function os.capture that does the equivalent of shell backquoting,
>   in shell-speak `...` or $(...).  It is 10 lines of Lua but requires
>   io.popen.
> 
>   A function os.quote that takes a Lua string and quotes it using
>   Bourne shell conventions, so that I can easily use string.format to
>   make commands that I can pass to os.execute.  This one is even
>   shorter:
>     local quote_me = '[^%w%+%-%=%@%_%/]' -- complement what doesn't need quotes
> 
>     function os.quote(s)
>       if s:find(quote_me) or s == '' then
>         return "'" .. string.gsub(s, "'", [['"'"']]) .. "'"
>       else
>         return s
>       end
>     end
> 
> I have a handful of others, like an os.execv, which takes a list,
> quotes every element, and then uses os.execute(table.concat(args, ' ')).
> But really just the three things above carry me a long way.

Would it be an idea to collect those in a lib so we might find those in
linux/bsd distros? It could be called "sh".


module(..., package.seeall)

-- shell utility library

function quote(s)
	-- complement what doesn't need quotes
	local quote_me = '[^%w%+%-%=%@%_%/]' 
	if s == nil then
		return nil
	end
	if s:find(quote_me) or s == '' then
		return "'"..string.gsub(s, "'", [['"'"']]).."'"
	else
		return s
	end
end

function execv(...)
	local _, i
	local args = {}
	for _, i in ipairs{...} do
		table.insert(args, quote(i))
	end
	return os.execute(table.concat(args, ' '))
end

function capture(cmd)
	p = io.popen(cmd)
	if p == nil then
		return nil
	end
	local ret = p:read("*all")
	p:close()
	return ret
end