Construct Shell Command and Run in Function

I am trying to construct a command out of the function arguments and run it. Here is an failed example

function display_file(fn, method)
    cmd = join([method, fn], " ")

It seems you cannot run the whole command from interpolation

display_file("test.txt", "cat")

ERROR: IOError: could not spawn `‘cat test.txt’`: no such file or directory (ENOENT).

I think it is because it requires the command to be not quoted? Like, `cat ‘test.txt’` is valid.

I tried to convert the string to the cmd object by macro @cmd.

function display_file(fn, method)
    cmd = join([method, fn], " ")
    cmd = @cmd cmd

It didn’t let me make the function

ERROR: LoadError: MethodError: no method matching shell_parse(::Symbol; special="#{}()<>|&*?~;")

I am not very sure how the macro works. Thank you for your help.

join creates a string, and when you interpolate that into the cmd it will be quoted (as indicated by the error, note the single quotes in

could not spawn `'cat test.txt'`

Why do you have to use join at all? This works:

function display_file(fn, method)
    run(`$method $fn`)

Thanks for the reply.

The one you suggested works on the “cat” command. Originally I was trying to do the following

display_file("", "wget")

It can start downloading without issues. But when I add parameters for wget

display_file("", "wget -np -nH")

It returns error

ERROR: IOError: could not spawn `'wget -np -nH'`: no such file or directory (ENOENT)

What should be the correct way to do it?

It’s again the same issue; you input a String which will be quoted when you interpolate that in a cmd. Instead you can input a cmd, and interpolate that, e.g. this should work:

display_file("https://www.....pdf", `wget -np -nH`)

Thanks a lot. That works nicely.

Just want to know a bit more to understand

display_file("https://www.....pdf", "wget")

Why using String “wget”, it can correctly interpolate as command?

Because there is nothing in the string "wget" that needs to be guarded with a quote, e.g. no spaces in this case.