如何分配定界符值在Bash中的变量? [英] How to assign a heredoc value to a variable in Bash?

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

问题描述

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

I have this multi-line string (quotes included)

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

我怎么会在Bash中使用定界符把它分配给一个变​​量?

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

我需要preserves换行。

我不想逃避字符串中的字符,这将是恼人的...

推荐答案

您可避免无用的使用和处理不匹配的报价与这更好的:

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

如果您在回声它不引用变量,新行会丢失。它引用preserves他们:

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"''

如果你想在源$ C ​​$ C使用缩进可读性,越少,thans后使用破折号。缩进必须只使用标签(无空格)来完成。

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"''

相反,如果你想preserve在结果变量的内容选项卡,你需要从 IFS 删除标签。对于终端标记此处DOC( 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"''

标签可以在命令行通过pressing插入<大骨节病>控制 - <大骨节病> V <大骨节病>标签。如果您使用的是编辑,取决于哪一个,那或许也可以,或者你可能要关闭该自动转换选项卡空间中的功能。

Tabs can be inserted at the command line by pressing Ctrl-V Tab. 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中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆