2014-10-06 100 views
2

我想運行嵌套for循環使用列表作爲其循環計數器。問題是,一旦'三角洲'循環達到100,它不會重置爲0.同樣的問題'邊'。嵌套for循環計數器重置

我試過了,但它似乎不適用於我的循環。 http://tldp.org/LDP/abs/html/nestedloops.html

這裏的任何想法?這裏是我的代碼:

#!/bin/sh 

threads="1 2 4 8 16 32 64 96 128 160 192 224 256" 
delta="0 10 20 30 40 50 60 70 80 90 100" 
edges="16 8192" 
nodes="16384" 

for threads in $threads 
do 
    for delta in $delta 
    do 
     for edges in $edges 
     do 
      for nodes in $nodes 
      do 
       printf "\n" 
       echo $threads 
       echo $delta 
       echo $edges 
       echo $nodes 
      done 
     done 
    done 
done 

預期輸出:

1 0 16 16384 
1 0 8192 16384 
1 10 16 16384 
1 10 8192 16384 
1 20 16 16384 
1 20 8192 16384 
+0

如果這是您的預期*輸出,那麼腳本是正確的,因爲這是它現在輸出的內容。 – Travis 2014-10-06 22:19:09

+0

我想要內循環再次從0開始(從它們列表的第一個元素開始),一旦外循環完成每次迭代 – masab 2014-10-06 22:25:01

+0

好吧,我現在知道我們有預期的輸出。 – Travis 2014-10-06 22:30:26

回答

2

當使用for圈就是這樣,請確保您給循環變量比你迭代變量不同的名稱。

使用for threads in $threads使區分循環變量(threads)和您正在循環的事件($threads)變得混淆。

當您稍後致電echo $threads時,bash不知道您指的是第一個。

在這種情況下,你可以改變環路聲明來像for n in nodesfor t in threads,然後echo$n$t最裏面的循環中,以獲得所需的輸出。

+0

我不知道如何改變它。 我需要13 * 10 * 2 * 1的迭代。在節點中做n,然後回顯$ n不會將循環計數器重置爲0 ... – masab 2014-10-06 22:38:02

+0

我不確定「將循環計數器重置爲0」是什麼意思。但是,進行這些更改會爲我的系統帶來預期的輸出。 – Travis 2014-10-06 22:41:40

+0

你能想象這是這樣的: 每個for循環應該是這樣的 爲(I = 0; I <10;我++) 對於(j = 0;Ĵ<10; J ++) 現在如果用完C中的腳本就像這樣,那麼j循環將在外循環的每次迭代中從0開始。我想在這個腳本中:) – masab 2014-10-06 22:49:44