如何在Bash中将Heredoc值分配给变量?

我有这个多行字符串(包括引号): bash

abc'asdf"
$(dont-execute-this)
foo"bar"''

如何在Bash中使用Heredoc将其分配给变量? 编辑器

我须要保留换行符。 this

我不想转义字符串中的字符,这很烦人... spa


#1楼

我发现本身必须读取其中包含NULL的字符串,所以这是一个解决方案,它将读取您在其中抛出的任何内容。 尽管若是您实际上正在处理NULL,则将须要在十六进制级别进行处理。 命令行

$ cat> read.dd.sh 3d

read.dd() {
     buf= 
     while read; do
        buf+=$REPLY
     done < <( dd bs=1 2>/dev/null | xxd -p )

     printf -v REPLY '%b' $( sed 's/../ \\\x&/g' <<< $buf )
}

证实: code

$ . read.dd.sh
$ read.dd < read.dd.sh
$ echo -n "$REPLY" > read.dd.sh.copy
$ diff read.dd.sh read.dd.sh.copy || echo "File are different"
$

HEREDOC示例(带有^ J,^ M,^ I): 文档

$ read.dd <<'HEREDOC'
>       (TAB)
>       (SPACES)
(^J)^M(^M)
> DONE
>
> HEREDOC

$ declare -p REPLY
declare -- REPLY="  (TAB)
      (SPACES)
(^M)
DONE

"

$ declare -p REPLY | xxd
0000000: 6465 636c 6172 6520 2d2d 2052 4550 4c59  declare -- REPLY
0000010: 3d22 0928 5441 4229 0a20 2020 2020 2028  =".(TAB).      (
0000020: 5350 4143 4553 290a 285e 4a29 0d28 5e4d  SPACES).(^J).(^M
0000030: 290a 444f 4e45 0a0a 220a                 ).DONE

#2楼

VAR=<<END
abc
END

不起做用,由于您将标准输入重定向到无关的东西,即分配 字符串

export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A

能够,可是里面有一个小问题,可能会阻止您使用它。 另外,您应该避免使用反引号,最好使用命令替换符号$(..)it

export A=$(cat <<END
sdfsdf
sdfsdf
sdfsfds
END
) ; echo $A

#3楼

使用$()将cat的输出分配给您的变量,以下所示:

VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)

# this will echo variable with new lines intact
echo "$VAR"
# this will echo variable without new lines (changed to space character)
echo $VAR

确保以单引号分隔END_HEREDOC开头。

请注意,此行末尾定界符END_HEREDOC必须单独存在(所以,圆括号末尾位于下一行)。

感谢@ephemient的回答。


#4楼

$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT

#5楼

您能够使用如下方法避免没必要要地使用cat并更好地处理不匹配的引号:

$ read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

若是您在回显变量时未引用该变量,则会丢失换行符。 引用它能够保留它们:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

若是要在源代码中使用缩进以提升可读性,请在小于号后使用破折号。 缩进必须仅使用制表符(不能使用空格)完成。

$ read -r -d '' VAR <<-'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
    EOF
$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

相反,若是您想将选项卡保留在结果变量的内容中,则须要从IFS删除选项卡。 此处文档( EOF )的终端标记不得缩进。

$ IFS='' read -r -d '' VAR <<'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
EOF
$ echo "$VAR"
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''

能够经过按Ctrl - V Tab在命令行中插入选项卡 。 若是您使用的是编辑器(取决于哪个),它也可能起做用,或者您可能必须关闭自动将制表符转换为空格的功能。

相关文章
相关标签/搜索