如何猫< >包含代码的文件? 如何猫< >包含代码的文件?(How

2019-05-09 02:57发布

我想用打印的代码到一个文件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

但是当我检查了文件输出,我得到这样的:

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

我试图把单引号,但输出也携带单引号吧。 如何避免这一问题?

Answer 1:

你只需要一个很小的变化; 单引号之后,这里的文档分隔符<<

cat <<'EOF' >> brightup.sh

或者等价反斜杠转义:

cat <<\EOF >>brightup.sh

如果没有引用,该文件在这里将进行变量替换,反引号将被评估,等等,就像你发现了。

如果您需要扩大一些,但不是全部,价值观,你需要单独逃避要防止的。

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

这里的文件

这种类型的重定向指示壳读取来自电流源的输入,直到仅包含定界符的线(没有尾随空白)被看见。 所有行的读取到该点,然后用作命令的标准输入。

在这里,文件的格式为:

  <<[-]word here-document delimiter 

没有参数扩展,命令替换,算术扩展,或路径扩展是在字执行。 如果word中任何字符被引用,分隔符是引用删除对词的结果,而在这里,文件中的行不会被扩展。 如果单词是无引号中,这里的文档的所有行进行参数扩展,命令替换和算术扩展 。 在后一种情况下,字符序列\被忽略,\必须使用引用字符\,$,和`。



Answer 2:

或者,使用EOF标记,你需要引用最初的标记,以便扩张不会做:

#-----v---v------
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

我ःŤः



Answer 3:

This should work, I just tested it out and it worked as expected: no expansion, substitution, or what-have-you took place.

cat <<< '
#!/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' > file # use overwrite mode so that you don't keep on appending the same script to that file over and over again, unless that's what you want. 

Using the following also works.

cat <<< ' > file
 ... code ...'

Also, it's worth noting that when using heredocs, such as << EOF, substitution and variable expansion and the like takes place. So doing something like this:

cat << EOF > file
cd "$HOME"
echo "$PWD" # echo the current path
EOF

will always result in the expansion of the variables $HOME and $PWD. So if your home directory is /home/foobar and the current path is /home/foobar/bin, file will look like this:

cd "/home/foobar"
echo "/home/foobar/bin"

instead of the expected:

cd "$HOME"
echo "$PWD"


文章来源: How to cat <> a file containing code?