我有这个多行字符串(包括引号):
abc'asdf"
$(dont-execute-this)
foo"bar"''
我将如何分配它到一个变量使用heredoc在Bash?
我需要保留换行符。
我不想转义字符串中的字符,这将是恼人的…
我有这个多行字符串(包括引号):
abc'asdf"
$(dont-execute-this)
foo"bar"''
我将如何分配它到一个变量使用heredoc在Bash?
我需要保留换行符。
我不想转义字符串中的字符,这将是恼人的…
当前回答
VAR=<<END
abc
END
不工作,因为你将stdin重定向到不关心它的东西,即赋值
export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A
有用,但里面有个背部痉挛可能会阻止你使用这个。另外,你应该避免使用反引号,最好使用命令替换符号$(..)。
export A=$(cat <<END
sdfsdf
sdfsdf
sdfsfds
END
) ; echo $A
其他回答
这里有一种非常优雅的方法,可以避免uoc:
VAR=$(sed -e 's/[ ]*\| //g' -e '1d;$d' <<'--------------------'
|
| <!DOCTYPE html>
| <html>
| <head>
| <script src='script.js'></script>
| </head>
| <body>
| <span id='hello-world'></span>
| </body>
| </html>
|
--------------------
)
'|'字符定义了空白,打印的字符串中只尊重空白右侧的空白。'1d;$d'去掉第一行和最后一行,它们只是作为内容周围的上下边距添加的。所有内容都可以缩进到您喜欢的任何级别,除了HEREDOC分隔符,在本例中它只是一堆连字符。
echo "$VAR"
# prints
<!DOCTYPE html>
<html>
<head>
<script src='script.js'></script>
</head>
<body>
<span id='hello-world'></span>
</body>
</html>
将heredoc值赋给变量
VAR="$(cat <<'VAREOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
VAREOF
)"
用作命令的参数
echo "$(cat <<'SQLEOF'
xxx''xxx'xxx'xx 123123 123123
abc'asdf"
$(dont-execute-this)
foo"bar"''
SQLEOF
)"
感谢dimo414的回答,这展示了他的伟大解决方案是如何工作的,并表明你可以在文本中轻松地使用引号和变量:
示例输出
$ ./test.sh
The text from the example function is:
Welcome dev: Would you "like" to know how many 'files' there are in /tmp?
There are " 38" files in /tmp, according to the "wc" command
test.sh
#!/bin/bash
function text1()
{
COUNT=$(\ls /tmp | wc -l)
cat <<EOF
$1 Would you "like" to know how many 'files' there are in /tmp?
There are "$COUNT" files in /tmp, according to the "wc" command
EOF
}
function main()
{
OUT=$(text1 "Welcome dev:")
echo "The text from the example function is: $OUT"
}
main
$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT
VAR=<<END
abc
END
不工作,因为你将stdin重定向到不关心它的东西,即赋值
export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A
有用,但里面有个背部痉挛可能会阻止你使用这个。另外,你应该避免使用反引号,最好使用命令替换符号$(..)。
export A=$(cat <<END
sdfsdf
sdfsdf
sdfsfds
END
) ; echo $A