1

I am already doing a for loop inside all my directories starting with abcd and it is working. But when I have other files or stuff in the root directory, it crashes after the first 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;

could somebody help me repair it?

1 Answer 1

4

The glob itself can be restricted to directories, at which point you can simply skip to the next iteration if the cd fails.

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

pushd and popd make changing directories and changing back simpler. (Since you don't do anything between the two popds, you can replace the second pushd with a simple cd and drop the corresonding popd.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.