Assign output of external command to julia variable

Dear all,
how can I assign the output of a shell pipeline to a julia’s variable?
Let’s say I have this pipe:

$ grep 'above' textExample.txt | head -1 | cut -d " " -f 4
blessed
$ x=$(grep 'above' textExample.txt | head -1 | cut -d " " -f 4)
$ echo $x
blessed

how do I assign the pipeline’s output blessed to a variable like I did with shell? I tried:

julia> x = readall(run(pipeline(`grep 'above' textExample.txt`),
       `head -1`, `cut -d " " -f 4`))
ERROR: MethodError: no method matching spawn_opts_inherit(::Cmd, ::Cmd)
Stacktrace:
 [1] #run#503(::Bool, ::Function, ::Cmd, ::Cmd, ::Vararg{Cmd,N} where N) at ./process.jl:662
 [2] run(::Cmd, ::Cmd, ::Vararg{Cmd,N} where N) at ./process.jl:661
 [3] top-level scope at none:0

Thanks

You may have a typo in your pipeline declaration. This works for me in Julia v1.1.0:

p = pipeline(`grep 'above' textExample.txt`, `head -1`, `cut -d " " -f 4`)
x = read(run(p))

You are using read instead of readall; is this because it is Julia 1+ wherease the example I have seen was from a previous version?
Anyway, by copying the text from here to avoid typos, I got:

julia> x = read(run(p))
blessed
ERROR: MethodError: no method matching read(::RawFD)
Closest candidates are:
  read(::Base.DevNull, ::Type{UInt8}) at coreio.jl:12
  read(::IOStream) at iostream.jl:481
  read(::IOStream, ::Type{UInt8}) at iostream.jl:393
  ...
Stacktrace:
 [1] read(::Base.ProcessChain) at ./io.jl:231
 [2] top-level scope at none:0
julia> x
Process(`ls`, ProcessExited(0))

julia> print(x)

julia> x = readall(run(p))
blessed
ERROR: UndefVarError: readall not defined
Stacktrace:
 [1] top-level scope at none:0
julia> x
Process(`ls`, ProcessExited(0))

both with read and readall, the julia variable does not contain the shell output…

Anyway, you were right: there is a typo in the command: a ) too much at the first newline and a ) less at the very end; anyway, neither readall nor read are defined methods when I run them:

julia> x = readall(run(pipeline(`grep 'above' textExample.txt`,
              `head -1`, `cut -d " " -f 4`))
              )
blessed
ERROR: UndefVarError: readall not defined
Stacktrace:
 [1] top-level scope at none:0

blessed
blessed

blessed comes out though. Is there a package that I need to load?

I don’t think you should mix read and run. This works for me on Julia 1.0.

julia> read(pipeline(`date`, `tr " " _`), String)
"fre_26_apr_2019_17:07:42_CEST\n"
4 Likes

Yep: you are right!

julia> x = read(pipeline(`grep 'above' textExample.txt`,
              `head -1`, `cut -d " " -f 4`), String)
"blessed\n"

I just need to remove the trailing newline. Thank you.

julia> readchomp(pipeline(`date`, `tr " " _`))
"fre_26_apr_2019_17:08:33_CEST"
1 Like