为什么这种递增的 for 循环会返回一个错误的变量?

der*_*cke 0 bash dash ash for

我正在尝试从 GRASS GIS 的 CLI 中调用这个 shell 脚本:

for (( day=5; day<367; day+5 )); do
  # commands that I've tested without a loop.
done
exit 0
Run Code Online (Sandbox Code Playgroud)

返回

Syntax error: Bad for loop variable
Run Code Online (Sandbox Code Playgroud)

Gil*_*il' 5

此错误消息来自ash。有几个shell 具有类似的语法。Ash 是一种相对基本的,专为小内存占用和快速执行而设计。另一个常见的外壳是Bash。Bash 具有更多功能。您发布的语法仅存在于 bash(以及其他一些 shell,但不存在 ash)中。

在灰烬中,你需要写¹:

day=5
while [ $day -lt 367 ]; do
  …
  day=$((day + 5))
done
Run Code Online (Sandbox Code Playgroud)

请注意,根据 Linux 发行版,/bin/sh是 ash 或 bash(一些异国情调的可能使用其他实现)。如果您正在编写使用 bash 语法的脚本,请务必放在#!/bin/bash顶部。

¹假设您的意思是day+=5您写的地方day+5,否则就是无限循环。