bash - 嵌套 For 循环计数器重置

标签 bash shell ubuntu nested-loops

我正在尝试运行使用列表作为循环计数器的嵌套 for 循环。问题是,一旦“增量”循环达到 100,它不会重置为 0。“边缘”也有同样的问题。

我尝试过这个,但它似乎不适用于我的循环。 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 

最佳答案

当使用这样的 for 循环时,请确保为循环变量指定与要迭代的变量不同的名称。

对 $threads 中的线程使用 会使区分循环变量 (threads) 和要循环的对象 ($threads)。

当您稍后调用 echo $threads 时,bash 不知道您指的是第一个线程。

在这种情况下,您可以将循环声明更改为 for n in nodesfor t inthreads,然后 echo out最内层循环内的 $n$t 以获得所需的输出。

关于bash - 嵌套 For 循环计数器重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225604/

相关文章:

docker volume 屏蔽容器中的父文件夹?

ruby-on-rails-3 - gem install pg 只能作为 sudo

linux - 如何逐行读取文件并为每行创建一个与每行最后一个单词相同的文件名的新文件?

linux - 如何在bash中获取多个目录的大小?

python - 如何使用 python 进行 tar 备份

linux - 比较文本文件中列出的文件

apache - 站点不存在 : Flask app on Apache 2. 4.29 Ubuntu 18.04

bash - 如何修复 "ERROR:buffer_manager.cc(488)] [.DisplayCompositor]GL ERROR :GL_INVALID_OPERATION : glBufferData:"

bash - 通过putty(ssh)连接发送和执行脚本

shell - 为什么 find 在传递当前目录与路径时返回不同的排序结果?