Home > OS >  System.get_env in elixir and new line (\n)
System.get_env in elixir and new line (\n)

Time:11-22

~ ❯ 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?

CodePudding user response:

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")

CodePudding user response:

This is really a shell question, not an elixir question. See this related answer that shows how to set a new line in an environment variable in bash. Using it from elixir:

$ TEST_KEY=$'hello\nworld' elixir -e 'IO.puts(System.get_env("TEST_KEY"))'
hello
world
  • Related