Skip to content

Commit 3f63661

Browse files
committed
feat: exit with error when run_cmd command fails
1 parent d6be868 commit 3f63661

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

lsblk.lua

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,24 @@ local VERSION = "0.3.0"
4545
--- Utility functions ---
4646
-------------------------
4747

48+
-- Print an error message to standard error and exit.
49+
local function fail(exit_code, format_string, ...)
50+
io.stderr:write("lsblk: " .. format_string:format(...) .. "\n")
51+
os.exit(exit_code)
52+
end
53+
4854
-- Execute a shell command and return its output as an array of lines.
4955
local function run_cmd(cmd)
5056
local f = io.popen(cmd .. " 2>/dev/null", "r")
5157
local lines = {}
5258
for line in f:lines() do
5359
table.insert(lines, line)
5460
end
55-
f:close()
61+
local result, _, status = f:close()
62+
if result == nil then
63+
fail(1, "command %q failed with status %d", cmd, status)
64+
end
65+
5666
return lines
5767
end
5868

@@ -506,11 +516,6 @@ options:
506516
Only output information about ZFS pools and datasets]])
507517
end
508518

509-
-- Print an error message to stderr.
510-
local function print_error(format_string, ...)
511-
io.stderr:write(format_string:format(...) .. "\n")
512-
end
513-
514519
------------
515520
--- Main ---
516521
------------
@@ -538,12 +543,10 @@ local function main()
538543
zfs = true
539544
elseif argument:match("^-") then
540545
-- Reject unknown options.
541-
print_error("lsblk: invalid option %q", argument)
542-
os.exit(2)
546+
fail(2, "invalid option %q", argument)
543547
else
544548
-- Reject any positional argument.
545-
print_error("lsblk: too many arguments")
546-
os.exit(2)
549+
fail(2, "too many arguments")
547550
end
548551
end
549552

0 commit comments

Comments
 (0)