bash - 如何正常地在 git action 的 sh 中随机运行 for 循环?

标签 bash sh github-actions

如何才能正常地在 git action 的 sh 中随机运行 for 循环?

这里有一个 github 存储库,每天都有提交。

github 操作

下面的 yml 文件存在。

name: planting-grass

on:
   schedule:
     - cron: '0 0 * * *'

jobs:
  task:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set current date
        id: date
        run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
      - name: Execute commands
        run: sh ./task.sh ${{ steps.date.outputs.date }}
      - name: Commit files
        run: |
          git config --global user.name "$(git --no-pager log --format=format:'%an' -n 1)"
          git config --global user.email "$(git --no-pager log --format=format:'%ae' -n 1)"
          git add date.txt
          git commit -m ${{ steps.date.outputs.date }}
      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}

这个yml运行task.sh。 task.sh 看起来像这样:

#!/bin/bash

echo "DATE: $1" >> date.txt

一切正常。

但是,在data.txt中,每天累积一行。

我想在 data.txt 中累积 1 到 100 行。

在哪里可以编辑以使用上述功能?

然后我尝试了以下方法:

#!/bin/bash

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

while [ "$i" -le "$number" ]; do
    echo "DATE: $1" >> date.txt
done
#!/bin/bash

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

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

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

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

但都失败了。

它输出以下错误消息:

./task.sh: 7: [: Illegal number:
./task.sh: 7: [[: not found
./task.sh: 7: i: not found

我想知道如何运行正常的随机 for 循环。

最诚挚的问候!

编辑)

#!/bin/bash

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

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

上面的代码工作正常,但只工作一次。 与想要在 1 到 100 之间随机运行 echo "DATE: ${i}">> date.txt 不同,它始终只执行一次。我们该如何解决这个问题?

最佳答案

  • 您可以将 run: sh ./task.sh 更改为 run: bash ./task.sh 以使用 bash 运行脚本,而不是 sh

  • 如果您的脚本是可执行的(chmod a+x task.sh,并提交文件),并且您有正确的 shebang (#!/bin/bash),您也可以执行 run: ./task.sh

  • 您的 cron 计划 (0 0 * * *) 设置为每天运行。如果你想更频繁地运行,你可以改变它。例如 0,30 * * * * 将每半小时运行一次(日期将全天相同,除非您包含时间,例如 date + '%Y-%m% d_%H:%M:%S')。

关于bash - 如何正常地在 git action 的 sh 中随机运行 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69973005/

相关文章:

linux - 如何逐行读取变量?

linux - 如何在 bash 中读取字符串或将整数转换为字符串?

git - 在 GitHub 操作中获取当前分支并提交哈希

linux - 使用 awk 检查来自不同行的变量

java - 如何在 build.gradle 文件中使用 GitHub secret 或 GitHub 环境变量

python - 当项目中任何位置的 python 文件(.py)发生更改时,如何运行 github 操作测试?

bash - 编译Blender BPY : recompile with -fPIC?

bash - 从文件 B 中删除文件 A 中的所有匹配项

Bash 在双换行符上拆分文件

windows - WSL2 : Launching VSCode from the command line using a *. 代码工作区文件