On Wed, 19 Sep 2012 21:03:11 -0500, Martin McCormick wrote:
>       I just discovered a knowledge deficiency on my part that
> I can't seem to resolve.
> 
>       If one writes a loop of the following form:
> 
> #!/usr/local/bin/bash 

Just a sidenote: If you're not using bash-specific functionality
and intend to make your script portable, use #!/bin/sh instead.



> ls -LF |grep \/ >/tmp/files
> while read dirname; do

Attention: "dirname" (/usr/bin/dirname) is a binary!



> cd $dirname
> #Do whatever commands to be repeated in each directory.
> done < /tmp/files
> 
>       This works quite well but it is shall we say sloppy
> because it creates a file that then must be cleaned up and its
> name needs to be made unique, etc.

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).



>       The standard output of the `ls -LF |grep \/` command
> needs to look like a file and all should be well. I thought the
> < redirection would pickup the standard output.

No, the > and < redirections basically operate on files,
while pipes redirect strandard output to standard input.
So for example,
        
        somecommand < /tmp/somefile

refers to a file that has to exist, while

        somecommand < `someothercommand`

does not take someothercommand's output (stdout), but instead
interprets it as a file specification and then reads from that
files (if existing).




-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
_______________________________________________
freebsd-questions@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-questions
To unsubscribe, send any mail to "freebsd-questions-unsubscr...@freebsd.org"

Reply via email to