Reputation: 110072
I use the Windows command tree
often to print out a tree diagram of the contents of files. I'd like to add this to my workflow in R but can't get the command to run though system
or shell.exec
and can't figure out why. Here is a reproducible example with 4 approaches and error messages using shQuote
(with and without) in system
and shell.exec
command. When I use cat
I can paste the command to the Windows command line manual (not using R) and the tree diagram is produced. What am I doing incorrectly that I can't make this run in R?
## build some mock files and directories with lapply
lapply(file.path("TEMP", c("", "X", "Y")), dir.create)
lapply(file.path("TEMP", paste0(c("A", "B"), ".txt")), file.create)
## create path to external file
out <- file.path(getwd(), "TREE.txt")
## create the tree command
cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
cat(cmd) ## view it
system(cmd) ## attempt 1
cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
shell.exec(cmd) ## attempt 2
cmd2 <- paste("tree", file.path(getwd(), "TEMP"), "/f /a >", out)
system(cmd2) ## attempt 3
shell.exec(cmd2) ## attempt 4
cat(cmd, file="clipboard")
## > out <- file.path(getwd(), "TREE.txt")
## > cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
## > cat(cmd)
## tree "C:/Users/trinker/Desktop/TEMP" /f /a > "C:/Users/trinker/Desktop/TREE.txt">
## > system(cmd)
## Too many parameters - >
## >
## > cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
## > shell.exec(cmd)
## Error in shell.exec(cmd) :
## 'tree "C:/Users/trinker/Desktop/TEMP" /f /a > "C:/Users/trinker/Desktop/TREE.txt"' not found
## >
## >
## > cmd2 <- paste("tree", file.path(getwd(), "TEMP"), "/f /a >", out)
## > system(cmd2)
## Too many parameters - >
## > shell.exec(cmd2)
## Error in shell.exec(cmd2) :
## 'tree C:/Users/trinker/Desktop/TEMP /f /a > C:/Users/trinker/Desktop/TREE.txt' not found
Upvotes: 2
Views: 1134
Reputation: 44585
Use shell
. On Windows, system
does not use a shell (it only runs system commands). You're trying use a pipe to redirect output, thus you encounter the problem noted in ? system
:
command
must be an executable (extensions ‘.exe’, ‘.com’) or a batch file (extensions ‘.cmd’ and ‘.bat’): these extensions are tried in turn if none is supplied.) This means that redirection, pipes, DOS internal commands, ... cannot be used: seeshell
if you want to pass a shell command-line.
Upvotes: 5