I'm trying to replicate a shell command in R and cannot figure out how to string commands together. This just returns the contents of the working folder (system()
fails for some reason):
> shell("dir")
Volume info ..
Directory of E:\Documents\R
contents are listed..
Now lets try and navigate to C drive and run dir
(without using the obvious dir C:
)..
> shell("cd C:")
C:\
> shell("dir")
Volume in drive E is GT
etc..
So it seems commands can't be entered separately as the shell doesn't remember the working directory. So..
> (cmd = "cd C:
+ dir")
[1] "cd C:\ndir"
> shell(cmd)
C:\
No luck as the C: folders are not reported. Other methods I've tried also fail. Grateful for any ideas.
Click Start, type cmd, and press Enter to open a command prompt window. In the Windows taskbar, right-click the command prompt window icon and select Command Prompt. A second command prompt window is opened.
Instead of scheduling multiple Windows Tasks that may overlap, use the "start /wait" command a batch file (. bat) to automatically run multiple commands in sequential order.
The documentation explains why system
doesn’t work: it executes the command directly on Windows, without spawning a shell first.
shell
(or better, system2
) is the way to go but as you’ve noticed, shell
will always spawn a new shell so that changes to the environment don’t carry over. system2
won’t work directly either since it quotes its commands (and thus doesn’t allow chaining of commands).
The correct solution in this context is not to use a shell command to change the directory. Use setwd
instead:
setwd('C:')
system2('dir')
If you want to reset the working directory after executing the command, use the following:
local({
oldwd = getwd()
on.exit(setwd(oldwd))
setwd('C:')
system2('dir')
})
I'm on Linux and this works for me:
system("cd ..;ls")
in navigating to the previous directory and running ls/dir there. In your case, on Windows, this apparently works:
shell("cd C: & dir")
or to get the output as a character vector:
shell("cd C: & dir", intern=T)
and on Linux: system("cd ..; ls", intern=T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With