如何对<<< EOF>>>包含代码的文件? [英] How to cat <<EOF >> a file containing code?

查看:110
本文介绍了如何对<<< EOF>>>包含代码的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用cat <<EOF >>将代码打印到文件中:

I want to print code into a file using cat <<EOF >>:

cat <<EOF >> brightup.sh
!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
   curr=$((curr+406));
   echo $curr  > /sys/class/backlight/intel_backlight/brightness;
fi
EOF

但是当我检查文件输出时,我得到了:

but when I check the file output, I get this:

!/bin/bash
curr=1634
if [  -lt 4477 ]; then
   curr=406;
   echo   > /sys/class/backlight/intel_backlight/brightness;
fi

我尝试用单引号引起来,但是输出中也带有单引号.我该如何避免这个问题?

I tried putting single quotes but the output also carries the single quotes with it. How can I avoid this issue?

推荐答案

您只需要进行最小的更改即可;在<<之后单引号here-document分隔符.

You only need a minimal change; single-quote the here-document delimiter after <<.

cat <<'EOF' >> brightup.sh

或等效的反斜杠转义:

cat <<\EOF >>brightup.sh

不加引号,这里的文件将进行变量替换,反引号将被评估,依此类推.

Without quoting, the here document will undergo variable substitution, backticks will be evaluated, etc, like you discovered.

如果您需要扩展一些而非全部值,则需要逐个转义要阻止的值.

If you need to expand some, but not all, values, you need to individually escape the ones you want to prevent.

cat <<EOF >>brightup.sh
#!/bin/sh
# Created on $(date # : <<-- this will be evaluated before cat;)
echo "\$HOME will not be evaluated because it is backslash-escaped"
EOF

会产生

#!/bin/sh
# Created on Fri Feb 16 11:00:18 UTC 2018
echo "$HOME will not be evaluated because it is backslash-escaped"

根据 @fedorqui 的建议,这是man bash中的相关部分:

As suggested by @fedorqui, here is the relevant section from man bash:

此处文档

这种重定向指示外壳程序从 当前源,直到仅包含定界符(无 尾随空白).到该点为止的所有行都是 然后用作命令的标准输入.

This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

here-documents的格式为:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

无参数扩展,命令替换,算术扩展, 或对单词执行路径名扩展.如果单词中有任何字符 用引号引起来,定界符是去除单词上的引号的结果,并且 此处文档中的行未展开. 如果单词是 如果不加引号,则本文档的所有行均需接受参数 扩展,命令替换和算术扩展.在里面 在后一种情况下,字符序列\被忽略,而\ 必须使用引号\,$和`.

No parameter 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. In the latter case, the character sequence \ is ignored, and \ must be used to quote the characters \, $, and `.

这篇关于如何对&lt;&lt;&lt; EOF&gt;&gt;&gt;包含代码的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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