如何在bash此处抑制变量替换 [英] How to suppress variable substitution in bash heredocs

查看:65
本文介绍了如何在bash此处抑制变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个不受变量扩展约束的Heredoc?

Is it possible to create a heredoc that does not become subject to variable expansion?

例如

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

更新,我知道通过\转义.我实际的Heredoc中有很多变量-并且容易出错而且繁琐,无法全部使用.

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.

推荐答案

引用定界符:

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的格式为:

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

不对word执行任何参数和变量扩展,命令替换,算术扩展或路径名扩展. 如果 单词中的任何字符都用引号引起来,定界符是 Word上的引号删除,此处文档中的行是 如果未用word引起引用,则对本文的所有行进行参数扩展,命令 替换和算术扩展,字符序列 \将被忽略,并且必须使用\引用字符\, $和`.

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 `.

如果重定向运算符是<<-,则从输入行和包含该行的行中除去所有前导制表符 定界符.这样就可以将shell脚本中的here-documents 以自然的方式缩进. [添加了重点.]

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此处抑制变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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