Skip to content

Commit

Permalink
feat(sys): Add an method sh to run shell cmd simply
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Dec 25, 2024
1 parent aea6857 commit 6e51337
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
31 changes: 31 additions & 0 deletions examples/shell.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env eco

local sys = require 'eco.sys'

local stdout, stderr, err = sys.sh('date', '-u')
print('stdout:', stdout)
print('stderr:', stderr)

if err then
print('err:', err)
end

print('-----------------')

stdout, stderr, err = sys.sh('date -u >&2')
print('stdout:', stdout)
print('stderr:', stderr)

if err then
print('err:', err)
end

print('-----------------')

stdout, stderr, err = sys.sh('sleep 2', 1)
print('stdout:', stdout)
print('stderr:', stderr)

if err then
print('err:', err)
end
34 changes: 34 additions & 0 deletions sys.lua
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,40 @@ function M.exec(...)
}, exec_metatable)
end

-- stdout, stderr, err = sys.sh(cmd, timeout)
function M.sh(cmd, timeout)
assert(type(cmd) == 'string' or type(cmd) == 'table', 'cmd must be a string or table')

if type(cmd) == 'string' then
cmd = { '/bin/sh', '-c', cmd }
end

local p, err = M.exec(table.unpack(cmd))
if not p then
return nil, nil, err
end

local stdout, stderr

timeout = timeout or 30

stdout, err = p:read_stdout('*a', timeout)
if not stdout then
p:close()
return nil, nil, err
end

stderr, err = p:read_stderr('*a', timeout)
if not stderr then
p:close()
return stdout, nil, err
end

p:close()

return stdout, stderr
end

function M.signal(sig, cb, ...)
local w = eco.watcher(eco.SIGNAL, sig)

Expand Down

0 comments on commit 6e51337

Please sign in to comment.