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

How to export multi line environment variable by shell script

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

export MULTI_LINES="line1\nline2\nline3"

那我就用source来运行吧

source env.sh

当我检查环境变量时:

printenv | grep MULTI_LINES

显示

MULTI_LINES=line1\nline2\nline3

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

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

export MULTI_LINES=$'line1\nline2\nline3'

根据man bash

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

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

export MULTI_LINES="line1
line2
line3"