【问题标题】:Weird cat behaviour奇怪的猫行为
【发布时间】:2014-07-17 13:47:25
【问题描述】:

在函数内部,我会有多个回显,但我记得我可以执行cat << EOF,然后是要输出的文本,然后是 EOF。但是,它似乎只在 EOF 部分没有缩进时才起作用,像这样

init(){
    if [ conditionial ]; then
        cat << EOF
        this is some text
        this is more text
        this is even more text

EOF

但它不是这样工作的:

init(){ if [ conditionial ]; then cat << EOF this is some text this is more text this is even more text EOF

有什么想法吗?

【问题讨论】:

标签: bash function eof cat


【解决方案1】:

“Here document”终止符必须出现在行首,除非重定向操作符有- 后缀:

cat << END
this does not
  END
here, but rather here
END

对比:

cat <<- END
this one does end here
        END

(注意空格和制表符;一些较旧的 shell 变体不支持这一点)。

除此之外,另一个有用的技巧是处理此处文档中的扩展。如果结束词(在我上面的例子中是END,在你的例子中是EOF)被引用,扩展被禁止:

cat << E1
you are in a maze of twisty little directories: $PWD
E1
cat << 'E2'
you owe the Usenet Oracle $1.75 for the Tab.
E2

【讨论】:

    【解决方案2】:

    直到你问我才知道这一点,但你可以使用 &lt;&lt;-(注意 -)忽略前导 制表符(不是空格)。

    here

    【讨论】:

      【解决方案3】:

      EOF 必须在行首,它后面不能有任何东西,但行尾:

      #! /bin/bash
      function say_hello {
              cat << EOF
              hello
              world
      EOF
      } 
      

      执行:

      bash test.sh
              hello
              world
      

      cat -A一起近距离观察:

      cat -A  test.sh
      #! /bin/bash$
      $
      function say_hello {$
      ^Icat << EOF$
      ^Ihello$
      ^Iworld$
      EOF$
      }$
      $
      say_hello$
      

      我的脚本有问题,在EOF 之后有空格并且无法工作,只有cat -A 我可以识别空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        相关资源
        最近更新 更多