猫> somefile<< " EOF"或者EOF,在bash shell上产生不同的结果

时间:2016-04-01 08:44:57

标签: bash shell

我编写了以下shell脚本:

#!/bin/sh

TEST_VAR="HELLO"

cat > test-1.txt << EOF
TEST_VAR is ${TEST_VAR}
EOF

cat > test-2.txt << "EOF"
TEST_VAR is ${TEST_VAR}
EOF

但我发现结果不同:

test-1.txtTEST_VAR is HELLO

test-2.txtTEST_VAR is ${TEST_VAR}

有人可以帮忙解释一下吗?

2 个答案:

答案 0 :(得分:0)

"EOF"会自动转义所有特殊字符,并按原样打印,EOF不会,因此会输入值。

您可以使用"EOF"代替\EOF

答案 1 :(得分:0)

以下行中的&#34; 导致问题:

cat > test-2.txt << "EOF"

原因在于 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

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

   If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter.  This allows here-documents within shell scripts
   to be indented in a natural fashion.
相关问题