2014-11-15 105 views
2

我正在创建一个脚本来检查目录中的3个文件,获取它们中的行数和邮件,如果行存在。我必须发送只有一个邮件,如果任一这些文件有计数,我最终发送3封邮件。shell脚本检查具有不同名称的多个文件

For Ex。我有这些文件

process_date.txt 
thread_date.txt 
child_date.txt 

荫做这样的事情

$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 

回答

1

你可以用你的脚本函数中的每mailx后使用return命令,就像这样:

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 
+0

谢谢@pwes ... :) – Naaz

1

试试这个:

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 
+0

@ Pranab:谢谢。 :-) – Naaz

2

正如你所说的你的问题,似乎你只需要检查是否至少有一个文件是非空的:你不需要计算行数。在Bash中,您可以使用[[ -s file ]]测试来准确测试file是否存在且非空。所以,你可以这样做:

#!/bin/bash 

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

您将称之为:

#!/bin/bash 

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

更一般地,你可以有邮件,如果作为参数给出的文件中的至少一个存在且非空发as

scriptname process_date.txt thread_date.txt child_date.txt 
+0

@ PM2Ring Oooops,你是对的!谢谢编辑 –

+0

@ gniourf_gniourf,我只需要发送一封邮件(如果文件有记录,即3个文件有记录或2个文件或1个),它必须是一个普通的邮件。邮件不应该被复制。 – Naaz

+1

@Naaz:但是这个脚本只能发送1封邮件,因为''break'命令。你可以通过'echo abc.com'替换'mailx abc.com'来测试它。 –

相关问题