bash Shell Scripting Question
freebsd at edvax.de
Thu Sep 20 02:29:48 UTC 2012
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:
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).
for DIR in `ls -LF | grep \/`; do
# do stuff
Or you can use piping:
ls -LF | grep \/ | while read DIR; do
# do stuff
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).
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
More information about the freebsd-questions