lua-users home
lua-l archive

Re: Issue using quoted arguments on os.execute() on Windows

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


2013年11月17日 Peter Cawley <lua@corsix.org>:
> The end effect of these rules is that if you want the sensible
> behaviour of quotes being preserved, and you want this consistently,
> then your command line mustn't start with a quote character. To that
> end, my personal approach is to do `os.execute("type NUL && "..cmd)`
> rather than `os.execute(cmd)`.
What I'm doing to circumvent the problem is simply to add outer quotes
if the command contains quotes. This doesn't require type, doesn't
require NUL, doesn't create an extra process for every command run.
Simply:
if os.getenv('OS')=='Windows_NT' then
 local execute = os.execute
 function os.execute(command)
 if command:match('"') then
 command = '"'..command..'"'
 end
 return execute(command)
 end
end
and of course you can write smarter wrappers, for example:
function execute(...)
 local t = {}
 for i=1,select('#', ...) do
 local s = tostring(t[i])
 if s:match('"') then s = '"'..s..'"' end
 t[i] = s
 end
 local command = table.concat(t, ' ')
 if command:match('"') then command = '"'..command..'"' end
 return os.execute(command)
end
execute(table.unpack{
 'copy',
 root .. 'app.exe',
 [[C:\Program Files\App]],
})
That's already short, but I'm sure you can add many more features with
one line of code each.

AltStyle によって変換されたページ (->オリジナル) /