2017-04-04 101 views
1

我已經在做所有我的目錄for loop內部從abcd它開始工作。但是當我在根目錄中有其他文件或東西時,它會在第一次循環後崩潰。bash for循環所有目錄並執行內部命令

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; 

有人可以幫我修理嗎?

回答

3

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化妝改變目錄和變回簡單。 (由於您在兩個popd之間沒有執行任何操作,因此可以用簡單的cd替換第二個pushd,並刪除相應的popd。)