How to redirect the output of run to a file

MWE: suppose I wanted to do something equivalent to the shell command

ls /tmp > /tmp/list

in Julia. I came up with

open(io->run(pipeline(`ls /tmp`, stdout=io)), "/tmp/list", "w")

but I fear that I am overcomplicating it.

1 Like

So, is there an answer to that question? I just came across that issue and I am wondering how to redirect in a run command.

You can use the @capture_out macro from Suppressor.jl, then write it to a file:

using Suppressor

output = @capture_out run(`ls`)

open("/var/log/myprogram.txt", "w") do io
    write(io, output)

Ah, thanks, interesting. This looks complicated though.

The following seems to work, but I am not sure how to deal with more complex commands (e.g. with &> etc)

  run(pipeline(`ls /tmp`, stdout = "/tmp/list"))

The |> operator used to work for redirection, but the feature seems to have been removed.

1 Like

This is the most julian:

julia> open("out.txt", "w") do file                      
           write(file, readstring(`ls -l`))              
shell> cat out.txt                                       
total 13                                                 
-rw-r--r-- 1 Ismael 197609 1203 Nov  4 00:17  
-rw-r--r-- 1 Ismael 197609  791 Nov  4 05:44   
-rw-r--r-- 1 Ismael 197609   25 Nov  4 00:17 REQUIRE     
-rw-r--r-- 1 Ismael 197609 2195 Nov  4 00:17 appveyor.yml
-rw-r--r-- 1 Ismael 197609    0 Nov  4 12:40 out.txt     
drwxr-xr-x 1 Ismael 197609    0 Nov  4 00:17 src         
drwxr-xr-x 1 Ismael 197609    0 Nov  4 00:17 test        

Nice. Even shorter:

    write("output.txt", readstring(`ls -l`))

Neat! I didn’t know about that. :smiley:

Can someone post an update of this? readstring is no longer available in Julia 1.0.

Just do

write("out.txt", read(`ls -l`))