Open HenrikBengtsson opened 5 years ago
Actually, this is not fully true. If there are backslashes in the values, they need to be escaped or strings need to be quoted, e.g.
FOO1=ABC \DEF
FOO2='ABC \DEF'
FOO3="ABC \DEF"
FOO4=ABC \\DEF
gives:
> Sys.getenv(c("FOO1", "FOO2", "FOO3", "FOO4"))
FOO1 FOO2 FOO3 FOO4
"ABC DEF" "ABC \\DEF" "ABC \\DEF" "ABC \\DEF"
Also, multiple quoted string are concatenated:
FOO1=ABC \DEF GHI
FOO2='ABC \DEF' 'GHI'
FOO3="ABC \DEF" 'GHI'
FOO4=ABC \\DEF GHI
> Sys.getenv(c("FOO1", "FOO2", "FOO3", "FOO4"))
FOO1
"ABC DEF GHI"
FOO2
"ABC \\DEF GHI"
FOO3
"ABC \\DEF GHI"
FOO4
"ABC \\DEF GHI"
It would be useful to also add a few examples on how to use what's mentioned in ?Startup
:
Lines in a site or user environment file should be either comment lines starting with
#
, or lines of the formname=value
. The latter sets the environmental variable name to value, overriding an existing value. If value contains an expression of the form${foo-bar}
, the value is that of the environmental variablefoo
if that exists and is set to a non-empty value, otherwisebar
. (If it is of the form${foo}
, the default is""
.) This construction can be nested, so bar can be of the same form (as in${foo-${bar-blah}}
). Note that the braces are essential: for example$HOME
will not be interpreted.
For example, adding the following to ~/.Renviron
(or a file under ~/.Renviron.d/
):
R_ENVVAR_TEST_001=HOME=${HOME},USER=${USER},R_HOME=${R_HOME}
will result in:
> Sys.getenv("R_ENVVAR_TEST_001")
[1] "HOME=/home/alice,USER=alice,R_HOME=/usr/lib/R"
Regarding equal signs in values; all of the below:
BAR1=ABC=DEF
BAR2="ABC=DEF"
BAR3=ABC\=DEF
result in the same env var values;
> Sys.getenv("BAR1")
[1] "ABC=DEF"
> Sys.getenv("BAR2")
[1] "ABC=DEF"
> Sys.getenv("BAR3")
[1] "ABC=DEF"
A best practice that'll work the same across platforms is to quote all environment variable values. For example,
A="ABC DEF"
B="${APPDATA}/FOO"
will work as expected, whereas:
A=ABC DEF
B=${APPDATA}/FOO
will not work if APPDATA
contains escaped symbols, e.g. \
, \n
, \t
, ...
See also https://stat.ethz.ch/pipermail/r-devel/2021-October/081164.html
Document format of
.Renviron
files. For instance, quotation marks are optional, e.g. all of the following give the same value"ABC DEF"
:In R,
UPDATE 2019-04-27: The code used for
base::readRenviron()
is in https://github.com/wch/r-source/blob/trunk/src/main/Renviron.c