gpt4 book ai didi

bash - 如何将 heredoc 值分配给 Bash 中的变量?

转载 作者:行者123 更新时间:2023-11-29 08:37:04 26 4
gpt4 key购买 nike

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

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

我如何在 Bash 中使用 heredoc 将它分配给一个变量?

我需要保留换行符。

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

最佳答案

您可以避免无用地使用 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 在命令行中插入制表符。如果您使用的是编辑器,这可能也有效,或者您可能必须关闭自动将制表符转换为空格的功能,具体取决于哪个编辑器。

关于bash - 如何将 heredoc 值分配给 Bash 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1167746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com