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

查看:33
本文介绍了如何猫<<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

或等效地反斜杠转义它:

or equivalently backslash-escape it:

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:

这里的文档

这种类型的重定向指示 shell 从当前源直到一行只包含分隔符(没有尾随空格)可见.到该点读取的所有行都是然后用作命令的标准输入.

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.

此处文档的格式为:

      <<[-]word
              here-document
      delimiter

无参数扩展、命令替换、算术扩展、或对 word 执行路径名扩展.如果单词中有任何字符被引用,分隔符是在单词上删除引用的结果,并且here-document 中的行没有扩展.如果词是未引用,此处文档的所有行都受参数影响扩展、命令替换和算术扩展.在里面后一种情况,字符序列 被忽略,而 必须用于引用字符 $`.

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 <newline> is ignored, and must be used to quote the characters , $, and `.

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

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