如何使用bash中的单个循环处理多个级别的结果



我需要创建一个特定的循环,该循环将以某些节点描述一个带有其所有节点的网络。该循环将成为与主题无关的其他事物的一部分。如您所知,在网络中,一个节点连接到另一个节点,依此类推。我在单独的文件中有所有这些节点,我需要用循环处理它们。每个循环都会产生更多的结果,我需要执行更多的循环,并且数量成倍增加,直到达到断裂点为止。现在,我知道如何用像这样的50个嵌套循环来解决这个问题:

declare loopvarnode=($(some command to get list of nodes))
for a in ${loopvarnode[@]}
        do
        declare check1=($(grep ${a[@]} results.file))
        if [[ "$a" == "breaking point" ]]
        then echo "Match found"; break
        elif [[ ! $check1 -z ]]
        then continue
        fi
        echo ${a[@]} >> results.file
        declare loopvarnode1=($(same thing but now we look for results in what was provided by variable $a))
        for b in ${loopvarnode1[@]}
            do
            declare check2=($(grep ${b[@]} results.file))
            if [[ "$b" == "breaking point" ]]
            then echo "Match found"; break
            elif [[ ! $check1 -z ]]
            then continue
            fi
            echo ${b[@]} >> results.file
            declare loopvarnode2=($(same thing but now we look for results in what was provided by variable $b))
            for c in ${loopvarnode2[@]}
                do 
.....

在其中大约50个之后,我想我应该没事,但是也许有一种方法可以使用一个或两个循环进行正确的操作。

您可以使用递归函数,而不是复制式循环:

 //$1 is first list parameter. 
    function do_things {    
      for a in ${$1[@]}
      do
        declare check1=($(grep ${a[@]} results.file))
        if [[ "$a" == "breaking point" ]]
        then echo "Match found"; break
        elif [[ ! $check1 -z ]]
        then continue
        fi
        echo ${a[@]} >> results.file
        declare loopvarnode1=($(same thing but now we look for results in what was provided by variable $a))
        do_things loopvarnode1
      done
} 

类似的东西。

也只是为了纠正您的函数,将数组传递为参数不会直接起作用(我得到不良替代)。这就是它的工作方式:

function do_things {
    array=( "$@" )
  for a in ${array[@]}
  do
    declare check1=($(grep ${a[@]} results.file))
    if [[ "$a" == "breaking point" ]];
    then echo "Match found"; break
    elif [[ ! -z $check1 ]];
    then continue
    fi
    echo ${a[@]}
    x=$(( $x + 1 ))
    declare loopvarnode1=($(some stuff with $a))
    do_things ${loopvarnode1[@]}
  done }

相关内容

  • 没有找到相关文章

最新更新