0

In R how can I get an environment variable value, or a default value if the variable is not set?

I'm looking for something of the form:

Sys.getenv("FOO_KEY").withDefault("barValue")

There is a similar question which only asks how to get an environment variable that is sure to exist.

Thank you in advance for your consideration and response.

Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125
  • 2
    Is there are a reason you are avoiding something like `ifelse(Sys.getenv("FOO_KEY")=="", "defaultValue", Sys.getenv("FOO_KEY"))` ? It has to do the function call twice which isn't ideal in terms of performance (and technically creates a race condition) but mostly that's not going to matter. If it does then you could do `val <- Sys.getenv("FOO_KEY"); if(val=="") val <- "defaultValue"`, or similar. – SamR Aug 16 '22 at 16:53

1 Answers1

2

Just pass the default value to the unset argument:

Sys.getenv("FOO_KEY", unset = "barValue")

or simply

Sys.getenv("FOO_KEY", "barValue")
leogama
  • 898
  • 9
  • 13