【问题标题】:Getting Length of Array in Bash在 Bash 中获取数组的长度
【发布时间】:2016-04-23 05:29:51
【问题描述】:

我目前正在编写一个脚本,我想在其中使用数组长度作为条件参数。我可以像这样得到数组的长度:

myarr=$(squeue | grep cjones903 | awk '{print $3}' )
echo ${#myarr}

但这不起作用,因为我需要迭代地评估长度,以便在长度低于阈值时继续。

我希望能够做到这一点:

while [ length is > x] do;
sleep 60;
else:

【问题讨论】:

  • 数组长度由 bash 中的${#arrayname[@]} 找到。您可以使用for ((i = 0; i < ${#arrayname[@]}; i++)); do ...(其中$i=0, 1, 2, ...)或for i in "${arrayname[@]}"; do...($i=element1, element2, ...)遍历数组,不需要条件。
  • @DavidC.Rankin 我可以像第一个代码 sn-p 一样获得数组的长度。我想迭代地监控(squeue | grep cjones903 | awk '{print $3}' ) 的输出长度。在它低于某个计数后,我希望能够继续我的循环。
  • 哦,对不起,但同样适用。检查${#myarray[@]} > x。现在如上所述,myarr 是一个字符串变量,而不是一个数组,所以长度就是${#myarr} > x。要使 myarr 成为数组,您需要 myarr=( $(squeue | grep cjones903 | awk '{print $3}' ) )
  • @DavidC.Rankin 这将在我创建数组时给我长度,但它不允许迭代检查长度,对吗?在 bash 中可以吗?
  • 嗯,是的,是的。每次使用${#myarr} 检查条件时,它都会计算该点的长度。如果您给出一个更完整的示例来说明您正在尝试做什么,我很可能会向您展示如何或给您一个明确的说明是否可行。哦,还有,你的比较应该使用-gt或-lt等数字比较。

标签: arrays bash while-loop


【解决方案1】:

好的,因为我们似乎已经在 cmets 中将其缩减为一种通过检查您的 squeue 调用返回的行数来检查正在运行的作业数量的方法,这是我在此期间修改的一个小脚本讨论。从中获得任何进一步的想法。要进一步研究的一件事是lock file(或lock dir),以确保一次只运行一个脚本实例(StackOverflow 上已有许多示例)。祝你好运:

#!/bin/bash

## consider setting lock file so only 1 instance runs
#  (many examples on SO)

## simple declarations
declare -i threshold=10             ## your limit, njobs above, sleep
declare -i njobs="$threshold"       ## threshold number of jobs limit
declare -i nseconds=60              ## seconds to sleep

while :; do     ## outer loop - runs perpetually

    njobs=$(squeue | grep cjones903 | wc -l)        ## get no. of jobs
    while ((njobs > threshold)); do                 ## test
        sleep "$nseconds"                           ## sleep if above
        njobs=$(squeue | grep cjones903 | wc -l)    ## get no. of jobs
    fi

    ## code to submit new batch of jobs here
    #  sleep a couple to let jobs distribute

done

exit 0

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 2015-08-05
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 2011-04-29
    相关资源
    最近更新 更多