diff --git a/base/process.jl b/base/process.jl index 6446dfdd12462..4bbeee16d796f 100644 --- a/base/process.jl +++ b/base/process.jl @@ -824,3 +824,11 @@ wait(x::Process) = if !process_exited(x); stream_wait(x, x.exitnotify); end wait(x::ProcessChain) = for p in x.processes; wait(p); end show(io::IO, p::Process) = print(io, "Process(", p.cmd, ", ", process_status(p), ")") + +# allow the elements of the Cmd to be accessed as an array or iterator +for f in (:length, :endof, :start, :eachindex, :eltype, :first, :last) + @eval $f(cmd::Cmd) = $f(cmd.exec) +end +for f in (:next, :done, :getindex) + @eval $f(cmd::Cmd, i) = $f(cmd.exec, i) +end diff --git a/doc/src/manual/running-external-programs.md b/doc/src/manual/running-external-programs.md index a179d9f5d006b..36e624f9f08f1 100644 --- a/doc/src/manual/running-external-programs.md +++ b/doc/src/manual/running-external-programs.md @@ -60,6 +60,18 @@ julia> open(`less`, "w", STDOUT) do io 3 ``` +The program name and the individual arguments in a command can be accessed +and iterated over as if the command were an array of strings: +```jldoctest +julia> collect(`echo "foo bar"`) +2-element Array{String,1}: + "echo" + "foo bar" + +julia> `echo "foo bar"`[2] +"foo bar" +``` + ## [Interpolation](@id command-interpolation) Suppose you want to do something a bit more complicated and use the name of a file in the variable diff --git a/test/spawn.jl b/test/spawn.jl index 84cccddbce632..d2bc79820ddf6 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -466,3 +466,14 @@ end Base.showerror(io::IO, e::Error19864) = print(io, "correct19864") throw(Error19864())'`), stderr=catcmd)) == "ERROR: correct19864" + +# accessing the command elements as an array or iterator: +let c = `ls -l "foo bar"` + @test collect(c) == ["ls", "-l", "foo bar"] + @test first(c) == "ls" == c[1] + @test last(c) == "foo bar" == c[3] == c[end] + @test c[1:2] == ["ls", "-l"] + @test eltype(c) == String + @test length(c) == 3 + @test eachindex(c) == 1:3 +end