如何通过shell脚本导出多行环境变量

Tia*_*Liu 6 shell environment-variables multiline

我有一个 env.sh 其中包含:

export MULTI_LINES="line1\nline2\nline3"
Run Code Online (Sandbox Code Playgroud)

然后我使用源来运行它

source env.sh
Run Code Online (Sandbox Code Playgroud)

当我检查环境变量时:

printenv | grep MULTI_LINES
Run Code Online (Sandbox Code Playgroud)

表明

MULTI_LINES=line1\nline2\nline3
Run Code Online (Sandbox Code Playgroud)

如何将“\n”转义为换行符?

anu*_*ava 8

如果使用bash,请使用此形式将\n其解释为换行符:

export MULTI_LINES=$'line1\nline2\nline3'
Run Code Online (Sandbox Code Playgroud)

按照man bash

该形式的单词 $'string'经过特殊处理。该单词扩展为字符串,并按照 ANSI C 标准指定的方式替换反斜杠转义字符。

或者您可以将值放在多行中:

export MULTI_LINES="line1
line2
line3"
Run Code Online (Sandbox Code Playgroud)