Error 'Syntax error: "(" unexpected' when declaring arrays in bash

Error 'Syntax error: "(" unexpected' when declaring arrays in bash

this OP 相同的问题,但必须是单独的原因。

以下脚本:

#!/bin/sh
arr=("cat" "dog" "bird")

交互式工作 (debian) 但在 crontab 调用时失败:

/bin/sh: 2: /path/zero_check.sh: Syntax error: "(" unexpected

我已经尝试使用 #!/bin/bash shebang,并使用 declare -a arr=("cat" "dog" "bird") 声明数组,但没有任何效果。

知道为什么吗?

在 crontab 条目中明确指定您的解释器。使用

bash /path/zero_check.sh

而不是

/path/zero_check.sh

这里的问题是你正在使用这个 shebang:

#!/bin/sh

arrays 是 Bash 特定的 shell 不允许的东西。

因此,要使其正常工作,请将脚本的 shebang 更改为 Bash:

#!/bin/bash

只是为了文档, 我有一个 运行 的旧脚本,它在 Shebang 中有一个语法错误:

#/bin/bash

而不是

#!/bin/bash

当然还要检查脚本是否可执行。

错误的 bash 函数声明存在非常相似的问题。这在命令行中工作正常,但它会导致 cron 失败...

function test () { ... }

Cron 应该保存 /var/mail

中的错误

我还建议使用“shellcheck”进行 linting,因为它发现了另一个我没有注意到的错误。