Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I'm trying to list all hidden directories with a "for" loop:

for i in ``ls -a | grep '^\.'` `;
do 
    echo $i
done

The problem is that the loop divides some directory names in two.

For example: ls -a | grep '^\.' gives me

.
..
.Deleted Items
.Drafts 
.Junk
.Junk E-mail
.Sent
.Sent Items
.Trash

But my loop gives me:

.
..
.Deleted
Items
.Drafts
.Junk
.Junk
E-mail
.Sent
.Sent
Items
.Trash

How do I improve my script, so that it doesn't divide directory names?

share|improve this question
    
You'll likely have better luck on Stack Overflow. –  gravyface May 23 '11 at 13:49
1  
    
Short of it use the IFS variable. tldp.org/LDP/abs/html/internalvariables.html –  Lmwangi May 23 '11 at 13:57

4 Answers 4

up vote 9 down vote accepted

You don't need the ls command as the shell will do the expansion for you and you should quote " the variable

for i in .*/
do
echo "$i"
done
share|improve this answer
    
But this work to : SAVEIFS=$IFS IFS=$(echo -en "\n\b") for i in ls -a | grep '^\.'; do echo "$i" done IFS=$SAVEIFS –  B14D3 May 24 '11 at 6:46

I ran into a similar problem some days ago and this thread was very helpful. Hope you find inspiration there.

share|improve this answer

Plenty of ways around this, from find, to extra quoting, etc.

Personally, I find it useful to modify the IFS variable. IFS is used to determine what the break character is between list items for for and the like. So, set IFS to be a newline via IFS=$'\n'. This will make the for loop read until the end of a line of input, before starting a new item in its list. It may not be the easiest way to solve this specific issue, (Iain's answer is more elegant) but I've found it quite useful in a number of situations.

share|improve this answer

Unless there's a specific need for 'for' you could try a while loop:

ls -d .* | while read Name  
do  
    echo "$Name"  
done  
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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