中为变量分配一个

中为变量分配一个

本文介绍了如何在 Bash 中为变量分配一个 heredoc 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this multi-line string (quotes included):

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

如何在 Bash 中使用 heredoc 将其分配给变量?

How would I assign it to a variable using a heredoc in Bash?

我需要保留换行符.

我不想转义字符串中的字符,那会很烦人...

I don't want to escape the characters in the string, that would be annoying...

推荐答案

你可以避免 cat 的无用使用,并更好地处理不匹配的引号:

You can avoid a useless use of cat and handle mismatched quotes better with this:

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

如果在回显变量时不引用它,换行符将丢失.引用它可以保留它们:

If you don't quote the variable when you echo it, newlines are lost. Quoting it preserves them:

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

如果您想在源代码中使用缩进以提高可读性,请在小于号后使用破折号.缩进必须仅使用制表符(无空格).

If you want to use indentation for readability in the source code, use a dash after the less-thans. The indentation must be done using only tabs (no spaces).

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

如果您想在结果变量的内容中保留制表符,则需要从 IFS 中删除制表符.此处文档的终端标记 (EOF) 不得缩进.

If, instead, you want to preserve the tabs in the contents of the resulting variable, you need to remove tab from IFS. The terminal marker for the here doc (EOF) must not be indented.

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

可以在命令行中按- 插入制表符.如果您使用的是编辑器,取决于哪一个,它也可能起作用,或者您可能必须关闭自动将制表符转换为空格的功能.

Tabs can be inserted at the command line by pressing - . If you are using an editor, depending on which one, that may also work or you may have to turn off the feature that automatically converts tabs to spaces.

这篇关于如何在 Bash 中为变量分配一个 heredoc 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 22:01