Create external command from string

are backticks the only way to construct a command for the ‘run’ function:

for example:

julia> cmd = “pwd”::String
“pwd”

julia> run($cmd)
/home/warmstrong
Process(pwd, ProcessExited(0))

julia>

what is the ` function?

Is there a way to create a command from a string with a function other than the backtick?

julia> Cmd(["ls", "-la"]) == `ls -la`
true
2 Likes

@cmd "ls -l" or Cmd(["ls", "-l"]) will do what you want (producing the `ls -l` command).

2 Likes

thanks. I think ‘Cmd’ is more readable.

Hi. I realise this is quite old, but Cmd() is not recognised (maybe deprecated?) and @cmd doesn’t seem to work very well. Even doing something simple like:
ls -lt | head
is something I cannot get to work. First trying
mycmd = @cmd “ls -lt | head”
Yields a warning that I should use quotes around the pipe:

mycmd = @cmd “ls -lt ‘|’ head”
is accepted, but then when I try
run(mycmd)
the response is

julia> run(mycmd)
ls: head: No such file or directory
ls: |: No such file or directory
ERROR: failed process: Process(ls -lt '|' head, ProcessExited(1)) [1]
[The shell seems to not see the pipe and looks for the file ‘head’ which isn’t there.]

Have there been any recent developments in this?

Both Cmd and @cmd still work.

The problem you are having is that ls -lt | head is a shell pipeline, but Cmd is not a shell — it is a way of launching individual programs. So, what you are doing is calling ls with filenames | and head, which is not what you want.

To construct a pipeline, see the pipeline documentation in the manual:

run(pipeline(`ls -l`, `head`))
3 Likes

Thanks Steven,

I will use that with @cmd

When I tried Cmd, I got below:

Cmd(“ls”)
ERROR: MethodError: no method matching Cmd(::String)

[must be something simple?]

You need to pass an array of strings to Cmd:

julia> Cmd(["ls"])
`ls`

Unfortunately this doesn’t seem to be documented.
Also, it would seem reasonable to allow a single string here.

4 Likes

The Cmd constructor takes an array of strings, as shown in my examples above.

1 Like

Thanks very much for clarifying!