How to cat < > a file containing code? Ask Question

How to cat < > a file containing code? Ask Question

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?

ベストアンサー1

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

will produce

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

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

Here Documents

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.

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

word に対しては、パラメータ展開、コマンド置換、算術展開、またはパス名展開は実行されません。word 内のいずれかの文字が引用符で囲まれている場合、区切り文字は word から引用符を削除した結果であり、ヒアドキュメント内の行は展開されません。wordが引用符で囲まれていない場合、ヒアドキュメントのすべての行はパラメータ展開、コマンド置換、および算術展開の対象となります。後者の場合、文字シーケンスは\<newline>無視され、、、および の文字\を引用符で囲むために使用する必要があります\$`

関連する問題については、以下も参照してください。https://stackoverflow.com/a/54434993

おすすめ記事