search sub folder with space in folder name using BASH

I am writing a shell script that iterates through a set IMAP folders.

Given:

WORKPATH=/var/mail/mydomain.com/myaccount/

I want to list all subfolders inside.

Easy with find:

for SUB_FOLDER in $(find "$WORKPATH" -type d)
do
    echo "SUB_FOLDER: $SUB_FOLDER"
done

However: Some of these folders have space in their name such as:

/var/mail/mydomain.com/myaccount/.Deleted Mails/
/var/mail/mydomain.com/myaccount/.Junk Mails/

Which make code above print out something in the neighbourhood of:

SUB_FOLDER: /var/mail/mydomain.com/myaccount/.Deleted
SUB_FOLDER: Mails/
SUB_FOLDER: /var/mail/mydomain.com/myaccount/.Junk
SUB_FOLDER: Mails/

I have tried using the -print0 option and pipe to xargs -0, but I have had no luck. Playing with IFS did even more bad things to output than needed.

Could really use a tip how make find make only 2 tokens to the for loop instad of 4, or alternative way to iterate the list.

Upvotes: 4

Views: 397

Answers (1)

Birei
Birei

Reputation: 36262

Use a while loop:

while read SUB_FOLDER; do 
    echo "SUB_FOLDER: $SUB_FOLDER"; 
done < <(find "$WORKPATH" -type d)

Upvotes: 6

Related Questions