~ ❯ export TEST_KEY='hello\nworld' && iex
iex(1)> System.get_env("TEST_KEY")
"hello\\nworld"
When running System.get_env/1
on a string with \n
it inserts an extra backslash, any way of preventing this behaviour?
It does not insert anything, it fairly reads the environment variable and, because backslashes are to be escaped in double-quotes, prints it as you see.
What you think is “new line” is nothing but the escape sequence. Here is an excerpts from e. g. echo
man:
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes
The default behaviour in raw shell:
❯ echo -E 'hello\nworld'
hello\nworld
The fact, that you see a new line there in echo
by default, or whatever is a side effect by the interpreter, whoever this interpreter is. The value itself contains a backslash and n
ASCII symbols, and no magic besides.
That said, if one wants to have new lines in place of \n
sequence in the value, one must apply the escaping themselves.
"TEST_KEY"
|> System.get_env()
|> to_string() # to NOT raise on absent value, redundant
|> String.replace("\\n", "\n")