[SWLUG] Stupidity with shell scripts

Gareth Bowker bowkerg at teccon.co.uk
Thu Mar 13 16:07:55 UTC 2003


On Thu, 2003-03-13 at 15:41, Chris M. Jackson wrote:
> Wrote myself a nice little shell script
> 
> #!/usr/bin/env bash
> # ^ because /bin/bash caused problems and locate works not
> for fname in `ls`
> do
>     sed -e "s%<br>%<br />%g" $fname
> done;
> 
> Now this worked, and changed all the relevant tags, however it dumped all
> to stdout.  I thought "Look, I forgot to write back to the file!"
> 
> Changed the important bit to
> 
>     sed -e "s%<br>%<br />%g" $fname > $fname
> 
> (the idea being that I thought it would write back)

don't write it straight back - write it to a temporary file first e.g.

sed -e "s%<br>%<br />%g" ${fname} > ${fname}.new
mv ${fname}.new ${fname}

will do it. My understanding is that when you're using
streams/redirection, it sets up all the programs in parallel pretty much
- e.g. at the same time as sed is being told to open $fname, bash is
opening $fname for (over)write, resulting in the empty files. You'll get
a similar effect if you ever try something like:

tar cvfz myfiles.tgz *

as this includes myfiles.tgz in the tar, so you get a nice little ,
whereby as myfiles.tgz grows, so does myfiles.tgz which needs to go
inside myfiles.tgz. If that makes sense!

Gareth





More information about the Swlug mailing list