We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Check the exit status from `System.cmd/3`
almirsarajcic
Check the exit status when wrapping an external command. A nonzero exit from the program does not make System.cmd/3 raise.
System.cmd("sh", ["-c", "printf 'conversion failed\\n' >&2; exit 7"],
stderr_to_stdout: true
)
#=> {"conversion failed\n", 7}
The command failed, but Elixir returned normally. A rescue block will not catch that exit status.
Translate the result explicitly at the boundary:
run = fn command, args ->
case System.cmd(command, args, stderr_to_stdout: true) do
{output, 0} -> {:ok, output}
{output, status} -> {:error, %{status: status, output: output}}
end
end
run.("sh", ["-c", "printf 'conversion failed\\n' >&2; exit 7"])
#=> {:error, %{output: "conversion failed\n", status: 7}}
stderr_to_stdout: true keeps the diagnostic text in the returned output. It does not change how failure is reported.
This wrapper treats zero as success. For tools with meaningful nonzero outcomes, handle those statuses according to the tool’s contract. Failure to start the executable, such as a missing program, can still raise.
The example uses a fixed shell script to reproduce failure; pass real executable arguments as a list rather than interpolating input into shell code.
copied to clipboard