# How to read from external command and also get exit status

**URL:** <https://discourse.julialang.org/t/how-to-read-from-external-command-and-also-get-exit-status/99880>\
**Category:** General Usage\
**Tags:** cmd\
**Created:** [June 5, 2023, 9:27am UTC](https://discourse.julialang.org/t/how-to-read-from-external-command-and-also-get-exit-status/99880 "2023-06-05T09:27:50Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![djvanderlaan](https://avatars.discourse-cdn.com/v4/letter/d/838e76/32.png) [@djvanderlaan](https://discourse.julialang.org/u/djvanderlaan)\
**Post date:** [June 5, 2023, 9:27am UTC](https://discourse.julialang.org/t/how-to-read-from-external-command-and-also-get-exit-status/99880/1 "2023-06-05T09:27:50Z")

</div>

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

```julia
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:

```julia
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.

---

<div class="post-metadata">

**Author:** ![jd-foster](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jd-foster/32/35824_2.png) [@jd-foster](https://discourse.julialang.org/u/jd-foster)\
**Post date:** [June 5, 2023, 1:18pm UTC](https://discourse.julialang.org/t/how-to-read-from-external-command-and-also-get-exit-status/99880/2 "2023-06-05T13:18:02Z")

</div>

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))`

---

<div class="post-metadata">

**Author:** ![djvanderlaan](https://avatars.discourse-cdn.com/v4/letter/d/838e76/32.png) [@djvanderlaan](https://discourse.julialang.org/u/djvanderlaan)\
**Post date:** [June 5, 2023, 1:33pm UTC](https://discourse.julialang.org/t/how-to-read-from-external-command-and-also-get-exit-status/99880/3 "2023-06-05T13:33:36Z")

</div>

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.
