grep in a loop

Hi ,

I am trying a script which takes user input userid . I am stuck how to check whether that is a valid user id or not in the audit log files. My code is :

cd $CCP_AUDIT
cat * > /export/home/$USR/l***/files
echo "UserId:\c"
read UserId

#Date Function
echo "DATE [YYYY-MM-DD] : \c"
read xxx

I need help in putting this in a loop:

grep $xxx /export/home/$USR/lalitha/files |grep -v Created |grep -v Rejecte
d | grep -i $UserId | Mail -s "Transactions for $UserId" ***@***.com
~
Thanks,
Gundu

With all the following, YM,aa,MV.

If I understand your problem correctly, you are trying to find all the log entries on a given date for a given user, then send an email to someone (probably yourself) to match all the transactions except Create and Reject.

You're asking specifically about putting the "grep" pipeline in a loop. This is not an especially big problem. Do you want to loop based on entering different user names? Different dates? Both? This simplest method is something like this (using /bin/sh):

while true; do
    read UserId
    read xxx
    grep [as you originally posted it]
done

(You probably want to put your prompts in as well --- this is just to show the general method.)

Then when you've run the program and for all the dates and userids, just hit control-C to break out of the loop.

More comments follow in another post.

Thanks,

I like the way it is giving me option , but if the userid is not there then i need to break out saying userid doesnot exist, how to do that??

Thanks,
Gundu

Your 'cat * > tempfile' is a classic UUOC (useless use of cat). There's nothing wrong with making '*' (without the apostrophes so it gets expanded) the "argument" to the first command in your pipeline.

Next, when you have four greps in a pipeline, you should consider using something like awk:

awk "/$xxx/ && /$UserId/ && !/Created/ && !/Rejected/" * | Mail ...

Notice the "double quotes" around the awk script are not 'apostrophes' --- you need your variables to be expanded. Of course, If you need a "$" in your search pattern, you're in for quoting experiments ...

(Added) I forgot to mention that this search is not case-insensitive, unlike your original grep.

Do you mean you want to break out of the loop if there is no log entry for a given user?

yes, i take the user input and check to see it is there in the log file for that date and userid, if not exit with echo doesn't exist

Thanks,
Gundu

I'm taking this to mean there are zero lines in the resulting output. (This is a different question than whether a given userid exists.)

Okay, this is where a temporary file begins to make sense: You need the same intermediate data for two different purposes. So change it this way:

grep ... > tempfile
if [ -s tempfile ]; then
    Mail ... < tempfile
else
    echo No such userid $UserId >&2
    break
fi
rm tempfile

Thank you very much for timely reply. It is working

Thanks,
Gundu