2

I am creating a script to check for 3 files in Directory, take the count of rows in them and mail if the rows exist.I have to send only one mail if either of these files have count, I am ending up sending 3 mails.

For Ex. I have these files

process_date.txt
thread_date.txt
child_date.txt

Iam doing something like

$1= process_date.txt
$2= thread_date.txt
$3= child_date.txt

if [ -f $1 ]
then
count1=`wc-l < $1`
if $count1 -ne 0 then mailx abc.com
fi
fi

if [ -f $2 ]
then
count2=`wc-l < $2`
if $count2 -ne 0 then mailx abc.com
fi
fi 

if [ -f $3 ]
then
count3=`wc-l < $3`
if $count3 -ne 0 then mailx abc.com
fi
fi
0

3 Answers 3

3

As you stated your question, it seems you only need to check whether at least one of the files is non-empty: you don't need to count the number of rows. In Bash, you may use the [[ -s file ]] test to exactly test whether file exists and is non-empty. So you can do:

#!/bin/bash

if [[ -s $1 ]] || [[ -s $2 ]] || [[ -s $3 ]]; then
    mailx abc.com
fi

More generally, you can have the mail sent if at least one of the files given as arguments exists and is non-empty:

#!/bin/bash

for file; do
    if [[ -s $file ]]; then
        mailx abc.com
        break
    fi
done

You'll call this as

scriptname process_date.txt thread_date.txt child_date.txt
Sign up to request clarification or add additional context in comments.

4 Comments

@ gniourf_gniourf, I need to send only one mail(if the file has records. i.e if 3 files have records or 2 files or 1) and it has to be a common mail.Mail should not be replicated.
@Naaz: But this script only sends 1 mail, due to thebreak command. You can test it by replacing mailx abc.com by echo abc.com
@Naaz: And if you want to get ultra-compact, gniourf_gniourf's 2nd script can be condensed down to a single line: for f;do [[ -s $f ]] && { mailx abc.com; break; } done
Thank You, thanks for resolving the situation @gniourf_gniourf
1

You can wrap your script in a function and use return command after every mailx, like this:

send_one_mail() {
  if [ -f "$1" ]
  then
    count1=$(wc -l < "$1")
    if [ $count1 -ne 0 ]
    then
      mailx abc.com
      return
    fi
  fi

  # etc. for other conditions

}

send_one_mail process_date.txt thread_date.txt child_date.txt

Comments

1

Try this:

if [ -f $1 ]
then
    count1=`wc -l < $1`
fi

if [ -f $2 ]
then
    count2=`wc -l < $2` 
fi 

if [ -f $3 ]
then
    count3=`wc -l < $3`
fi


if [ $count1 -ne 0 -o $count2 -ne 0 -o $count3 -ne 0 ]
then
    mailx abc.com
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.