geotheory
geotheory

Reputation: 23690

Multiple shell commands in Windows

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.

Upvotes: 8

Views: 2009

Answers (4)

imriss
imriss

Reputation: 1981

This is a solution from here. That solved my problem in calling the windows dir command:

system("cmd.exe /c dir", intern=TRUE) 

Upvotes: 0

Martin Dinov
Martin Dinov

Reputation: 8825

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)

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 546153

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')
})

Upvotes: 5

Mark Heckmann
Mark Heckmann

Reputation: 11441

Don't know if this helps, but collapsing the commands to one string when using system works on MacOS

cmds <- c("ls", "cd ..", "ls");
system(paste(cmds, collapse=";"))

Upvotes: 1

Related Questions