0

I have following part of code inside bash script.

for dir in $(find /etc/aaa -type d -maxdepth 1)
do
 #my code
done

#my code

if /etc/aaa directory is not present then i want to exit script with some error.

I am aware that i can test existence of directory before executing for loop.

But i want to know is there any other way (short way in for loop only) so that if directory /etc/aaa is not present then it should exit else script should continue.

In current situation, script give error of that find: /etc/aaa: No such file or directory and continues to remaining part after for loop.

Also exit status of for loop is 0.

  • Bad syntax on the find, the type should be "d" for directory rather than "dir" ? – steve Aug 17 '15 at 16:02
  • @steve thnx ..it was typo error – AVJ Aug 17 '15 at 16:11
0

You could do something like:

if dirs="$(find /etc/aaa -type dir -maxdepth 1 2> /dev/null)"; then
    for dir in ${dirs}; do
        # Your code
    done
    # Your code
else
    # find failed, generate error
fi
  • thnx for ur answer. It is helpful but can i put something like below instead of using if condition. "test -d /etc/aaa && for dir in $(find /etc/aaa -type dir -maxdepth ;do #my code ;done || exit 1" – AVJ Aug 17 '15 at 16:06
0

I do not understand why you would want to exit the loop in the middle of it's execution. I do not think it is worth executing the loop if the directory you desire is not present.

I think you should do something along the lines of:

if [ ! -d /etc/aaa ]; do
    echo "Error"
    exit 1
else
    for files in $(ls /etc/aaa); do
        # code
    done
    # more code
fi

If this is not at all what you are looking for, please explain what it is that you want to accomplish.

  • Be careful trying to parse ls as you'll run into problems with spaces in filenames and lots of other things. Also, your ls will get both files and directories in /etc/aaa, while it seems the OP only wants directories there – Eric Renouf Aug 17 '15 at 16:15
  • I appreciate the advice. This was simply an example for the OP showing how this could be handled. I had no intention of him/her to actually use the for loop. – Peschke Aug 17 '15 at 16:37
0

I think it is easier to do a logic test before the loop. But this is a hack n' slash into the for-statement:

for dir in `! find /etc/aaa -type d -maxdepth 1 2>/dev/null && echo error && exit`;
do
//your code
done

//your code

This will also suppress the stderr of find.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.