Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

env argument does not work in system2?

Tags:

r

r-faq

I am trying to run a command using system2 and to set an environment variable using the env argument, but it appears not to be set. I'm on Linux so this should work [in the helpfile it mentions that env sometimes doesn't work in Windows].

Does anyone know how to set environment variables in system32?

E.g.

system2('echo', args='foobar')
# foobar # as expected
system2('echo', args='$X', env="X=foobar")
#   # <-- nothing is printed. as if I had just done `echo`
# I expect to see 'foobar' echoed.

# pretty sure the above environment specification is right, but just in case
system2('echo', args='$X', env=c(X='foobar'))
# sh: 1: foobar: not found

# just to show it can work
system('X=foobar; echo $X')
# foobar

I will just use system as a workaround for now, but the system helpfile keeps going on about how I should be using system2. (If this is a bug, where do I file it?)

> sessionInfo()
R version 3.2.5 (2016-04-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu precise (12.04.5 LTS)

locale:
 [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8    
 [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8   
 [7] LC_PAPER=en_AU.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base  
like image 821
mathematical.coffee Avatar asked Dec 24 '22 00:12

mathematical.coffee


1 Answers

Since the command that goes to the shell is just paste(c(env, shQuote(command), args), collapse = " "), you can do:

system2("echo", args = "$X", env = c("X=foobar;"))
like image 157
Weihuang Wong Avatar answered Jan 01 '23 01:01

Weihuang Wong