如何在 bash heredocs 中抑制变量替换 [英] How to suppress variable substitution in bash heredocs
问题描述
是否可以创建一个不受变量扩展影响的heredoc?
例如
cat <<<-EOF >一些文件.sh不要打印 $1 的当前值,而是稍后对其进行评估.EOF
更新 我知道通过 进行转义.我的实际 heredoc 中有许多变量 - 逃避所有这些变量很容易出错且乏味.
引用分隔符:
cat <<<-"EOF" >一些文件.sh不要打印 $1 的当前值,而是稍后对其进行评估.EOF
这导致:
$ cat somefile.sh不要打印 $1 的当前值,而是稍后对其进行评估.
文档
<块引用>此处文档的格式为:
<<[-]word此处文档分隔符
不会对 word 执行参数和变量扩展、命令替换、算术扩展或路径名扩展.如果word 中的任何字符都被引用,分隔符是word上的引用删除,here-document中的行是不展开. 如果word不加引号,则here-document的所有行都进行参数展开,命令替换和算术扩展,字符序列 被忽略,并且 必须用于引用字符 ,$, 和`.
如果重定向操作符是 <<-,那么所有前导制表符都会从输入行和包含分隔符.这允许 shell 脚本中的 here-documents以自然的方式缩进.[强调.]
Is it possible to create a heredoc that does not become subject to variable expansion?
e.g.
cat <<-EOF > somefile.sh
Do not print current value of $1 instead evaluate it later.
EOF
Update I am aware of escaping by . My actual heredoc has many variables in it - and it is error prone and tedious to escape all of them.
Quote the delimiter:
cat <<-"EOF" > somefile.sh
Do not print current value of $1 instead evaluate it later.
EOF
This results in:
$ cat somefile.sh
Do not print current value of $1 instead evaluate it later.
Documentation
The format of here-documents is:
<<[-]word here-document delimiter
No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence is ignored, and must be used to quote the characters , $, and `.
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion. [Emphasis added.]
这篇关于如何在 bash heredocs 中抑制变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!