【问题标题】:Why are spaces required before a curly brace in a function definition?为什么函数定义中的花括号前需要空格?
【发布时间】:2018-11-14 22:55:09
【问题描述】:

我正在尝试创建一个 bash 脚本,将一堆 pdf 转换为文本以提取一些信息,但是 shell 给了我这个错误:

./AutoBib.sh: line 8: syntax error near unexpected token `pdftotext'
./AutoBib.sh: line 8: `    pdftotext $1 temp.txt'

这里有一个我的函数的例子:

function doi{

    pdftotext $1 temp.txt
    cat temp.txt | grep doi: | cut -d: -f 2 | head -n 1 >> dois.txt
    rm -rf temp.txt
}
doi $PDF

变量PDF 被输入。在添加它起作用的功能之前,我曾经在我的脚本中编写:

pdftotext $PDF tempo.txt

【问题讨论】:

    标签: bash function shell syntax


    【解决方案1】:

    来自 Bash manual

    大括号是保留字,所以必须从列表中分开 通过空格或其他 shell 元字符。

    function ... 是用于定义 Bash 函数的 outdated 语法。改用这个:

    doi() {
       ...
    }
    

    由于() 是元字符,在这种情况下您不需要空格(尽管空格使您的代码更漂亮):

    doi(){
      ...
    }
    

    稍微扩展一下,记住我们需要在{ 之后和命令grouping 中的 `}' 之前有一个空格(空格、制表符或换行符),如下所示:

    { command1; command2; ... }
    

    【讨论】:

      【解决方案2】:

      您需要在函数名称之后和 { 之前有一个空格:

      function doi {
                  ^
      

      【讨论】:

      • 对。 (好吧,严格来说,你不需要。Bash 允许你定义一个名为 doi{ 的函数——但是你需要在函数名之后加上一个 { 标记。)问题是 doi{ 是一个单一的令牌,而不是标识符 doi 后跟 { 令牌。
      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 2016-01-01
      • 2017-11-07
      • 2021-10-15
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      相关资源
      最近更新 更多