数组上的迭代

数组上的迭代

我需要创建脚本来检查池状态。每个池都会返回如下扫描结果:

pool1 - scan: scrub repaired 0 in 0 days 00:06:17 with 0 errors on Thu Sep 
pool2 - scan: scrub in progress since Thu Sep 
pool3 - scan: scrub repaired 0 in 0 days 00:04:02 with 0 errors on Thu Sep 
pool4 - scan: scrub repaired 0 in 0 days 00:04:22 with 0 errors on Thu Sep 

我需要迭代它们中的每一个并检查扫描是否完成。如果它们都包含 擦洗修复然后做某事。如果有一个或两个正在进行中,我需要检查它们,比如说每 5 秒检查一次,然后等待它们全部完成。到目前为止,我没有 do/until 循环:

declare -a scans=("pool1 - scan: scrub repaired 0 in 0 days 00:06:17 with 0 errors on Thu Sep" 
"pool2 - scan: scrub in progress since Thu Sep"
"pool3 - scan: scrub repaired 0 in 0 days 00:04:02 with 0 errors on Thu Sep" 
"pool4 - scan: scrub repaired 0 in 0 days 00:04:22 with 0 errors on Thu Sep"

for scan in "${scans[@]}"; do
    echo "$scan"
    if ![[ $scan == *"scrub repaired"* ]]; then
            echo "Scan in progress. Waiting.."
    elif [[ $scan == *"scrub repaired"* ]]; then
            echo "Scan is ready. Saving it somewhere for documentation"
            
    else
            continue
    fi
    break
done

答案1

您已经花了几个小时对此进行了一些研究,因此这里是一个未优化的解决方案,不会与您最初的想法相差太多。

#!/usr/bin/bash

declare -a scans=("pool1 - scan: scrub repaired 0 in 0 days 00:06:17 with 0 errors on Thu Sep" "pool2 - scan: scrub in progress since Thu Sep" "pool3 - scan: scrub repaired 0 in 0 days 00:04:02 with 0 errors on Thu Sep" "pool4 - scan: scrub repaired 0 in 0 days 00:04:22 with 0 errors on Thu Sep")

pools_to_complete=${#scans[@]}
pools_completed=0

while ! [ "$pools_completed" == "$pools_to_complete" ]; do
    pools_completed=$(grep -c "scrub repaired" < <(for scan in "${scans[@]}"; do printf "%s\n" "$scan";done))

    if [ "$pools_completed" == "$pools_to_complete" ]; then
        printf "All %s scans are complete. Saving it somewhere for documentation\n" "$pools_to_complete"
    else
        printf "Scan in progress. Waiting...\n"
        sleep 5
    fi
done

你可以做得比上面更好。我主要改变你的方法是:

  • 避免将每个池进程的执行跟踪(完成或未完成)存储在 Bash 数组中。数组很实用,但使 shell 脚本不可移植。
  • 将每条迹线存储在外部文件 ( ) 中,而不是数组,infile一条迹线存储在一行中。

用外部文件替换阵列需要对上述内容进行两个简单的修改:

  • 紧随“shebang”之后的两行被替换为:
    pools_to_complete=$(wc -l infile)
  • 块内的第一行while变成:
    pools_completed=$(grep -c "scrub repaired" < infile)

infile请注意,如果您坚持使用数组,以上所有内容都假设在数组组件中的每行或每个数组组件中只能有 0 或 1 个字符串“scrub Repaired”实例。这是因为grep -c ...计算搜索到的模式出现的次数。华泰

相关内容