gpt4 book ai didi

linux - 如何 cat <> 包含代码的文件?

转载 作者:IT老高 更新时间:2023-10-28 12:26:22 26 4
gpt4 key购买 nike

我想使用 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

我尝试使用单引号,但输出也带有单引号。我怎样才能避免这个问题?

最佳答案

您只需要很小的改动;在 << 之后单引号这里文档的分隔符.

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 的相关部分:

Here Documents

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

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 wordare quoted, the delimiter is the result of quote removal on word, andthe lines in the here-document are not expanded. If word isunquoted, all lines of the here-document are subjected to parameterexpansion, command substitution, and arithmetic expansion. In thelatter case, the character sequence \<newline> is ignored, and \must be used to quote the characters \, $, and `.

关于linux - 如何 cat <<EOF >> 包含代码的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com