【问题标题】:bash for loop all directories and execute command insidebash for循环所有目录并在里面执行命令
【发布时间】:2017-08-29 20:06:28
【问题描述】:

我已经在我所有以 abcd 开头的目录中创建了一个for loop,它正在工作。但是当我在根目录中有其他文件或东西时,它会在第一个循环后崩溃。

dir_1="./some/path1"
dir_2="./some/path2"
dir_3="./some/path3"

for f in ./abcd*;
    do      
        [ -d $f ] && cd "$f" && echo I am inside $f

        find $dir_1 -name something*.txt -exec cp {} $dir_3 \;
        find $dir_2 -name another*.txt -exec cp {} $dir_3 \;

        cd "$dir_3"
        # do some other stuff here
        cd ../../..     
    done;

谁能帮我修一下?

【问题讨论】:

    标签: bash shell unix for-loop


    【解决方案1】:

    glob 本身可以限制在目录中,此时如果cd 失败,您可以直接跳到下一个迭代。

    for f in ./abcd*/;
    do      
        pushd "$f" || continue
    
        find "$dir_1" -name something*.txt -exec cp {} "$dir_3" \;
        find "$dir_2" -name another*.txt -exec cp {} "$dir_3" \;
    
        pushd "$dir_3"
        # do some other stuff here
        popd
        popd
    done
    

    pushdpopd 使更改目录和改回更简单。 (由于您在两个popds 之间不做任何事情,您可以将第二个pushd 替换为简单的cd 并删除对应的popd。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      相关资源
      最近更新 更多