Date: Thu, 20 Sep 2012 04:29:45 +0200 From: Polytropon <freebsd@edvax.de> To: Martin McCormick <martin@dc.cis.okstate.edu> Cc: FreeBSD Questions <freebsd-questions@freebsd.org> Subject: Re: bash Shell Scripting Question Message-ID: <20120920042945.ed2edd11.freebsd@edvax.de> In-Reply-To: <201209200203.q8K23Bv5034624@x.it.okstate.edu> References: <201209200203.q8K23Bv5034624@x.it.okstate.edu>
next in thread | previous in thread | raw e-mail | index | archive | help
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, ...
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20120920042945.ed2edd11.freebsd>