Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple shell commands in Windows

Tags:

r

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.

like image 219
geotheory Avatar asked Jan 07 '14 14:01

geotheory


People also ask

Can you run 2 command prompts at once?

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.

How do I run multiple commands in one batch file?

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.


2 Answers

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')
})
like image 56
Konrad Rudolph Avatar answered Oct 18 '22 09:10

Konrad Rudolph


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)

like image 35
Martin Dinov Avatar answered Oct 18 '22 10:10

Martin Dinov