【问题标题】:Bash - while inside for loop not exitingBash - 内部 for 循环不退出
【发布时间】:2017-11-10 16:03:17
【问题描述】:

我是 bash 脚本的初学者。

我在当前工作目录 dir1-dir10 + script.sh + 一个名为“tocopyfile”的文件中有 10 个目录。

Dir1-10 为空。 tocopyfile 是用于我的培训目的的测试文本文件 script.sh 包含以下代码:

dir=`pwd`
i="0"
for directory in `ls $dir`;do
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
done

脚本应将文件“tocopyfile”的 10 个副本复制到命名约定 file# 中的每个目录 (dir1-10)。问题是脚本存在于第一个目录之后,而没有对剩余的剩余目录执行 while 循环。

谁能解释一下我做错了什么?

非常感谢您的帮助。

【问题讨论】:

    标签: bash shell loops for-loop while-loop


    【解决方案1】:

    当前的问题是您需要为外循环的每次迭代重置i 的值。

    for directory in `ls $dir`; do  # No! but more on that in a moment
        i=0
        while [ $i -le 10 ]
    

    您的代码还有一些其他问题。

    1. dir=$(pwd) 几乎总是毫无意义; bash 已经提供了一个变量PWD,其中包含当前工作目录的名称。不过,您实际上并不需要它;您可以简单地使用./*/ 展开到当前工作目录中的目录列表。

    2. 切勿在脚本中使用ls 的输出。

    3. $[...] 是过时的语法;请改用$((...))


    稍微清理一下你的代码,我们得到

    for directory in ./*/; do
        i=0
        while [ "$i" -le 10 ]; do
            cp tocopyfile "$directory/file$i" &
            i=$((i+1))
        done
    done
    

    【讨论】:

    • 谢谢。很有帮助
    【解决方案2】:

    您需要在for 循环中初始化$i 内部,这样$i == 0 在您的while 的每次迭代中:

    dir=`pwd`
    for directory in `ls $dir`;do
        i="0" # <===== notice the change here
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
    done
    

    您可能想要更改的其他内容:

    1. 用双引号括起所有变量(如果其中有空格)。
    2. 使用$() 而不是长期弃用的反引号语法。
    3. 使用 $(()) 代替已弃用的 $[] 语法。
    4. 整理缩进。

    【讨论】:

    • 感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多