循环在 git 动作中无法正常工作

Loop does not work normally in git action

循环在 git 操作中无法正常工作。

我的 task.sh 看起来像这样:

#!/bin/bash

range=100
number=$((RANDOM % range))

while [ "$i" -le "$number" ]; do
    echo "DATE: " >> date.txt
done

以上代码的结果为:

./task.sh: 6: [: Illegal number:

下面的代码工作正常。

echo "DATE: " >> date.txt

我尝试了以下,但它也给出了错误。

#!/bin/bash

range=500
number=$((RANDOM % range))

for ((run=1; run <= number; run++)); do
    echo 'hello'
done

我很好奇你是如何让像下面这样的命令正常工作的。

while (random(1-100)); do
     echo 'hello'
done

此致!

它应该适用于:

while [[ "$i" -le "$number" ]]; do
      ^^                    ^^

这需要 bash,但由于您的 shebang#!/bin/bash,您的 t.sh 脚本将 运行 与 bash,无论它的“.sh”扩展名。

但在目前的形式下,它将是一个无限循环。

您需要添加

i=$((i+1))

这会增加 $i 变量,使 "$i" -le "$number" 正常工作。

i 初始化为 0 是 better/cleaner,但是 [[ "" -le "$number" ]](在第一个循环中,仍然“有效”(因为空字符串被认为“低于或等于”一个非空的“$number”字符串,并保留在循环中)


话虽如此,该脚本的 form/usage 更正确(使用 arithmetic comparison):

#!/bin/bash

range=100
number=$((RANDOM % range))
i=0

while (( i <= number )); do
    echo "DATE: ${i}" >> date.txt
    i=$((i+1))
done

或者,使用 C 风格的循环

#!/bin/bash

range=100
number=$((RANDOM % range))

for ((i = 0 ; i < number ; i++)); do
    echo "DATE: ${i}" >> date.txt
done

所有这些都假定 bash,但作为 seen here, since for (( ... )) syntax isn't POSIX, it would not work with Alpine Linux or other OS where sh links to ash (Almquist shell) or Dash

在后一种情况下:

#!/bin/bash

range=100
number=$((RANDOM % range))

for i in $(seq 0 $number); do
    echo "DATE: ${i}" >> date.txt
done

您有两个不同的问题:

  1. 你是 运行 你的脚本 sh,而不是 bash
  2. 您没有分配 i

第一个,见Why does my Bash code fail when I run it with 'sh'?

对于第二个,在尝试将 $i 作为数字进行比较之前,在脚本中设置 i=0