r-lib / processx

Execute and Control Subprocesses from R
https://processx.r-lib.org/
Other
234 stars 43 forks source link

Not possible to combine commands? #322

Closed thiagoveloso closed 2 years ago

thiagoveloso commented 2 years ago

Sometimes I need to run nested commands on my Linux machine through R.

In pure command line, I would do something along the lines:

touch test1.txt && touch test2.txt

From within R, I try assembling the same command like this:

library(processx)
process$new("touch", c("test1.txt", "&&", "touch", "test2.txt"))

But it doesn't work as expected. It creates files test1.txt, &&, touch and test2.txt, whereas I would expect only test1.txt and test2.txt to be created.

What am I missing? Is this something I can achieve with processx?

gaborcsardi commented 2 years ago

At the command line, you have a shell, and the shell will interpret && and start the second touch process, if the first one was successful.

process$new starts a single process and it does not use a shell. You can start two processes if you want:

p1 <- process$new("touch", "test1.txt")
p1$wait()
p2 <- process$new("touch", "test2.txt")

You can also run a shell, and then the shell will support the && syntax:

process$new("sh", "touch test1.txt && touch test2.txt")

The latter is of course not portable, not all systems have sh.

thiagoveloso commented 2 years ago

Thanks @gaborcsardi, the second option is what I am looking for.

However, in order to get it right on my workstation I needed to change it slightly to:

library(processx)
process$new("bash", c("-c", "touch test1.txt && touch test2.txt"))

which is working as intended. Thanks for the hint!