我需要编写一个脚本,向程序(psql)输入多行输入。

在谷歌搜索了一下之后,我发现下面的语法是有效的:

cat << EOF | psql ---params
BEGIN;

`pg_dump ----something`

update table .... statement ...;

END;
EOF

这正确地构造了多行字符串(从BEGIN;to END;,包括在内)并将其作为输入管道输送到psql。

但是我不知道它是怎么工作的,有人能解释一下吗?

我主要指的是cat << EOF,我知道>输出到一个文件,>>附加到一个文件,<从文件读取输入。

<<到底是做什么的?

它有手册页吗?


当前回答

需要注意的是,cat << \EOT(参见反斜杠)不会展开内部的任何变量,而cat << EOT则可以。

例子:

FOO="bar"

cat << \EOT > foobar.txt
echo "$FOO"
EOT

将输出: echo $ FOO

而:

FOO="bar"

cat << EOT > foobar.txt
echo "$FOO"
EOT

将输出: 回声“酒吧”

其他回答

对上面的答案做一点扩展。后面的>将输入引导到文件中,覆盖现有内容。然而,一个特别方便的用法是双箭头>>追加,将您的新内容添加到文件的末尾,如:

cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert   /var/sharedFolder/sometin/vsdc/cert nfs
EOF

这将扩展fstab,而不必担心意外修改其中的任何内容。

这并不一定是对最初问题的回答,而是分享我自己测试的一些结果。这样的:

<<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

将生成与以下相同的文件:

cat <<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

所以,我不明白使用cat命令的意义。

创建json文件的示例:

cat << EoF > ./allaccess.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:*"
      ],
      "Resource": [
        "arn:aws:s3:::*"
      ]
    }
  ]
}
EoF

结果是:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:*"
      ],
      "Resource": [
        "arn:aws:s3:::*"
      ]
    }
  ]
}

这被称为heredoc格式,用于向stdin提供字符串。详情见https://en.wikipedia.org/wiki/Here_document#Unix_shells。


来自man bash:

Here Documents This type of redirection instructs the shell to read input from the current source until a line containing only word (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 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 `. 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.

需要注意的是,cat << \EOT(参见反斜杠)不会展开内部的任何变量,而cat << EOT则可以。

例子:

FOO="bar"

cat << \EOT > foobar.txt
echo "$FOO"
EOT

将输出: echo $ FOO

而:

FOO="bar"

cat << EOT > foobar.txt
echo "$FOO"
EOT

将输出: 回声“酒吧”