Home > Blockchain >  Getting a single output from multiple if/else outputs
Getting a single output from multiple if/else outputs

Time:12-15

I'm trying to get the line count of a few files in a directory by a script. Up until now I was able to do so with if/else statements but I'm getting an output for each file that is checked. My goal is to get a single "main" output that:

  • If all the outputs are "OK" ->> main output will be "OK"
  • If even one of the outputs is "PROBLEM" ->> main output will indicate an error.
files=`find /backup/external/logs -type f -daystart -ctime 0 -print | grep csv | grep -v Collateral`
count_files=`echo $files | grep -o " " | wc -l`
count_files=$((count_files 1))

for ((i=1;i<=${count_files}; i  ));
do
        file=`echo $files | awk -F " " -v a=$i '{ print $a }'`
        linecount=`(wc -l "$file"| awk '{print $1}')`

        if [ $linecount -gt "1" ]; then
         echo "OK"
        else
         echo "PROBLEM! File $file"
        fi
done

And my output is:

PROBLEM! File /backup/external/logs/log1_20211214010002.csv
PROBLEM! File /backup/external/logs/log2_20211214010002.csv
OK
PROBLEM! File /backup/external/logs/log4_20211214010002.csv
OK
PROBLEM! File /backup/external/logs/log6_20211214010002.csv

CodePudding user response:

Accumulate the problematic files in a variable.

problems=""
for ((i=1;i<=${count_files}; i  ));
do
    file=`echo $files | awk -F " " -v a=$i '{ print $a }'`
    linecount=`(wc -l "$file"| awk '{print $1}')`

    if [ $linecount -le 1 ]; then
        problems ="$file "
    fi
done
if [ "$problems" ] ; then
  echo Problems: "$problems"
fi

CodePudding user response:

It seems you want to report the csv files whose filenames don't contain "Collateral", which have exactly zero or one line. If so you do not need such a complicated script; this all could be done with a single find command:

find /backup/external/logs -type f -daystart -ctime 0 \
    -name '*.csv' \! -name '*Collateral*' \
    -exec bash -c '{ read && read || echo "PROBLEM! File $1"; } < "$1"' _ {} \;
  • Related