bash Shell Scripting Question

Jan Henrik Sylvester me at
Thu Sep 20 09:16:53 UTC 2012

On 09/20/2012 04:29, Polytropon wrote:
> Correct. You could use different approaches which may or may
> not fail due to the directory names you will encounter (like
> directories with spaces or special characters).
> 	#!/bin/sh
> 	for DIR in `ls -LF | grep \/`; do
> 		cd ${DIR}
> 		# do stuff
> 	done
> Or you can use piping:
> 	#!/bin/sh
> 	ls -LF | grep \/ | while read DIR; do
> 		cd ${DIR}
> 		# do stuff
> 	done
> I'm quite confident there are even more elegant and fault-
> tolerant solutions. You would maybe have to tweak the ls
> command or play with IFS (space or newline).

Even if you start quoting "${DIR}", the first one will fail at least for 
names containing spaces, the second one at least for names starting with 
spaces. As you said, you would have to change IFS to maybe slash and 
newline, assuming that you do not have names containing newlines, in 
which case the approach cannot work.

I understand that you want all directories and links to directories not 
starting with a period. How about trying all files not starting with a 
period and skipping the non directories:

for DIR in *
     cd "$DIR" >/dev/null 2>&1 || continue
     cd - > /dev/null

This one works with names containing spaces or even newlines and does 
not even need to spawn external commands or subshells. It may have other 
caveats, though.

Jan Henrik

More information about the freebsd-questions mailing list