David LeBauer
David LeBauer

Reputation: 31741

Why won't `system` create and return a variable?

In R, When I run

system("FOO='test123'")

I would expect

system("echo $FOO")

to return

test123

in the same way that

system("echo $USER") 

returns my username

But it returns nothing. Why is this?


Why would anyone want to do this? I was trying to simulate the use of env FOO='test1234 R -vanilla < script.R while writing script.R, which in turn calls system("echo $FOO)`

Upvotes: 2

Views: 163

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263357

I don't know R, but in other languages system() (at least on Unix-like systems) creates a new shell (/bin/sh) process to execute the command. Your FOO='test123' sets the value of $FOO, but only within that process. Your system("echo $FOO") executes in a new process in which $FOO hasn't been set.

If R has a way to set environment variables internally (setenv, perhaps?), you should use that instead.

EDIT: As @Joshua says in a comment, it's Sys.setenv.

Upvotes: 3

Marc B
Marc B

Reputation: 360732

Each system call will fire up a NEW shell, with its own environment. Variables set in one shell will not carry over to subsequent shells - they'll each be completely independent of each other.

Upvotes: 6

Related Questions