首页 > 解决方案 > 为什么函数定义中的花括号前需要空格?

问题描述

我正在尝试创建一个 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

标签: bashfunctionshellsyntax

解决方案


来自 Bash手册

大括号是保留字,因此必须用空格或其他 shell 元字符将它们与列表隔开。

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

doi() {
   ...
}

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

doi(){
  ...
}

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

{ command1; command2; ... }

推荐阅读