System.get_env 长生不老药和新行 (\n)
System.get_env in elixir and new line (\n)
~ ❯ export TEST_KEY='hello\nworld' && iex
iex(1)> System.get_env("TEST_KEY")
"hello\nworld"
当 运行 System.get_env/1
在带有 \n
的字符串上时,它会插入一个额外的反斜杠,有什么方法可以防止这种行为?
它不会插入任何内容,它会公平地读取环境变量,并且因为反斜杠要在双引号中转义,所以会打印出来。
你认为的“新行”只不过是转义序列。这是e的摘录。 G。 echo
男人:
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes
raw 中的默认行为 shell:
❯ echo -E 'hello\nworld'
hello\nworld
事实上,默认情况下您会在 echo
中看到一个新行,或者 解释器 的副作用,无论这个解释器是谁。该值本身包含反斜杠和 n
ASCII 符号,除此之外没有任何魔法。
就是说,如果想要用 新行 代替值中的 \n
序列,则必须自己应用转义。
"TEST_KEY"
|> System.get_env()
|> to_string() # to NOT raise on absent value, redundant
|> String.replace("\n", "\n")
这真是一道shell题,不是仙丹题。请参阅 this related answer,其中显示了如何在 bash 的环境变量中设置新行。从长生不老药中使用它:
$ TEST_KEY=$'hello\nworld' elixir -e 'IO.puts(System.get_env("TEST_KEY"))'
hello
world
~ ❯ export TEST_KEY='hello\nworld' && iex
iex(1)> System.get_env("TEST_KEY")
"hello\nworld"
当 运行 System.get_env/1
在带有 \n
的字符串上时,它会插入一个额外的反斜杠,有什么方法可以防止这种行为?
它不会插入任何内容,它会公平地读取环境变量,并且因为反斜杠要在双引号中转义,所以会打印出来。
你认为的“新行”只不过是转义序列。这是e的摘录。 G。 echo
男人:
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes
raw 中的默认行为 shell:
❯ echo -E 'hello\nworld'
hello\nworld
事实上,默认情况下您会在 echo
中看到一个新行,或者 解释器 的副作用,无论这个解释器是谁。该值本身包含反斜杠和 n
ASCII 符号,除此之外没有任何魔法。
就是说,如果想要用 新行 代替值中的 \n
序列,则必须自己应用转义。
"TEST_KEY"
|> System.get_env()
|> to_string() # to NOT raise on absent value, redundant
|> String.replace("\n", "\n")
这真是一道shell题,不是仙丹题。请参阅 this related answer,其中显示了如何在 bash 的环境变量中设置新行。从长生不老药中使用它:
$ TEST_KEY=$'hello\nworld' elixir -e 'IO.puts(System.get_env("TEST_KEY"))'
hello
world