How to read from external command and also get exit status

I would like to run an external command an get its output

str = read(`ls -al`, String)

works for reading the output. However, I have a command that can also give non-zero exit codes on what I consider successful execution (no results). So I want to run the command capture its output (if any) and capture the exit code. I have a solution which seems to work, but it also seems that there should be a simpler solution for this. This is my current solution:

function runandcapture(cmd)  
  io = IOBuffer();
  cmd = Cmd(cmd, ignorestatus = true)
  res = run(pipeline(cmd; stdout=io, stderr=io));
  str = String(take!(io))
  [str, res.exitcode]
end

str, res = runandcapture(`ls --foo`) 

Is this how this should be done? Can it be done simpler/better?

Thanks.

Hi and welcome to the forum. This looks about optimal to me for your described use. Happy to hear if other people have good ideas.

If you really don’t care about stderr, you can simplify the third line to
res = run(pipeline(cmd, io))

Thanks. I am still relatively new to julia so I occasionally wonder if what I am doing is the proper way of doing it. It was a bit surprising that read didn’t also return the exit value.