【问题标题】:How to suppress variable substitution in bash heredocs如何在 bash heredocs 中抑制变量替换
【发布时间】:2015-10-17 04:20:47
【问题描述】:

是否可以创建不受变量扩展影响的heredoc?

例如

cat <<-EOF > somefile.sh
Do not print current value of $1 instead evaluate it later.
EOF

更新我知道\ 转义。我实际的 heredoc 中有很多变量 - 逃避所有变量容易出错且乏味。

【问题讨论】:

  • 使用\$var 变量不会展开
  • 我不是这个意思。我会更新 OP。
  • 这对我来说也是个问题。由于在没有大量导出和子外壳废话的情况下无法在管道中识别函数,因此我在这里使用管道传输到临时文件的文档来定义辅助函数,这成为了一场寻宝,试图找出我在 heredoc 中没有逃脱的内容。

标签: bash syntax heredoc


【解决方案1】:

引用分隔符:

cat <<-"EOF"  > somefile.sh
Do not print current value of $1 instead evaluate it later.
EOF

这会导致:

$ cat somefile.sh 
Do not print current value of $1 instead evaluate it later.

文档

here-documents的格式为:

          <<[-]word
                  here-document
          delimiter

没有对 word 执行参数和变量扩展、命令替换、算术扩展或路径名扩展。 如果 word 中的任何字符都被引用,分隔符是 word 上的引号删除,here-document 中的行是 不展开。 如果 word 不加引号,则 here-document 的所有行都进行参数展开,命令 替换和算术扩展,字符序列 \ 被忽略,必须使用 \ 来引用字符 \, $,和`。

如果重定向操作符是

【讨论】:

  • 啊!这就是我一直在寻找的。​​span>
  • 不幸的是,这并不直观......但我很高兴它存在!
【解决方案2】:

在 $ 符号前加上反冲

$ VAR=XXX
$ cat << END
> dk
> \$VAR
> END
dk
$VAR

【讨论】:

  • 我知道这一点。我的heredoc 有很多——太容易错过一个或多个。
猜你喜欢
  • 2015-11-25
  • 2018-09-27
  • 2011-01-27
  • 2016-12-02
  • 2019-02-19
  • 2014-09-02
  • 2022-11-11
  • 1970-01-01
  • 2011-12-02
相关资源
最近更新 更多