Subject: | |
From: | |
Reply To: | |
Date: | Fri, 3 Aug 2007 18:19:41 -0400 |
Content-Type: | text/plain |
Parts/Attachments: |
|
|
On Aug 3, 2007, at 12:19 AM, David Livesay wrote:
> cat secure.log |
> while read line; do
> echo $line
> done
I spent a lot of time working on my script today because of a little
"gotcha" involved in using this method. Basically, the problem is, if
you initialize a variable before the cat command and then change its
value inside the while loop, its value will still be the initial
value after you exit the loop. Here's a script that demonstrates this:
#!/bin/sh -
PATH=/bin:/usr/bin:/sbin:/usr/sbin
cd /private/var/log
linecount=0
cat secure.log |
while read line; do
linecount=`expr $linecount + 1`
echo $linecount
done
echo $linecount
This isn't generally an issue with while loops. It only seems to
happen when you pipe the output of a command into a while loop. It
seems like the pipe spawns a new thread.
This arose because I had to account for the possibility that the
script might run on the first of a month when there are no entries
yet that start with that month, so you have to compare the date of
the last entry with the current month (e.g. date "+%b") before you
decide whether to archive the last batch of entries and create an
empty secure.log or write them back to secure.log. (If anybody is
interested in the new and improved version of the script, write me
off-list. The one I posted last night had a few problems.)
|
|
|