如何控制for循环?

2 bash

假设我们有“for循环”如下:

#!/bin/bash
for i in $(cat test_file); do 
echo $i
done
Run Code Online (Sandbox Code Playgroud)

文本文件的内容是父文件夹中的文件夹名称

如果 text_file 包含 10000 个条目(即变量 i),我如何告诉“for 循环”在每 10 个“回声”之间休眠 10 秒。换句话说,当 for 循环读取 text_file 中的变量 i 时,如何控制 for 循环可以在每个特定时间段运行的变量数量?所以输出如下:

   Variable #1
   Variable #2
   Variable #3
   .
   .
   .
   .
   sleep 10
    Variable #11
    Variable #12
    Variable #13
   .
   .       .
Run Code Online (Sandbox Code Playgroud)

Rom*_*est 6

使用以下bash脚本(每 10 个“回声”之间休眠 10 秒):

test.sh 是脚本的测试名称

#!/bin/bash
while ((++i)); read -r line
do
    echo "$line"
    if (( "$i" % 10 == 0)) 
    then
        sleep 10
    fi
done < $1
Run Code Online (Sandbox Code Playgroud)

用法

bash test.sh test_file
Run Code Online (Sandbox Code Playgroud)

while ((++i))-i每次read -r line从输入返回一行时都会增加计数器

if (( "$i" % 10 == 0))- 检查当前行号i是否可以被整除10(意味着执行流程到达接下来的 10 行)

sleep 10 - 暂停脚本 10 秒