0

I wrote a small bash script. It will try to find the word ERROR. If found the resulting value will be non-zero numeric (for example 25. I mentioned in the script but it is variable numeric value), and if not found, it will be 0.

My problem is: I want to use case statement, such that if output is not zero, then execute the following command

truncate -s 0 /root/test/wayfile.log && screen -X -S wowow quit &

Script here:

#! /bin/bash

case "$(grep ERROR /root/test/wayfile.log | wc -w)" in

25)  echo "empty log file and kill screen: $(date)" >> /var/log/finderror.txt
    truncate -s 0 /root/test/wayfile.log && screen -X -S wowow quit &
;;
0)  # all ok
;;
esac
4

One option: tell case to look for a 0, in which case: do nothing; otherwise, execute your command:

case X in
  (0) : ## do nothing
      ;;
  (*) truncate ...
      ;;
esac

Another option: tell case to look for any non-zero digit:

case X in 
  ([123456789]) truncate ...
esac

... but instead of trying to match numbers with case, I would use test:

if [ "$(grep -c ERROR /root/test/wayfile.log)" -gt 0 ]
then
  truncate ...
fi

I've simplified grep ... | wc -w to just grep -c, which asks grep to do the counting instead of involving wc.

Further, since you're really just interested in whether the word ERROR exists at all in the file, you can just ask grep if it's there:

if grep -F -q ERROR /root/test/wayfile.log
then
   truncate ...
fi

The -F flag tells grep that our search text is plain ("Fixed") text -- no regular expressions; the -q flag tells grep to be "quiet" -- don't count or output matching lines, just set its exit status based on whether it found the search text at all (or not). A successful exit code (of 0) indicates that the search text was found at least once in the file; failure indicates that the search text was not found at all in the file.

  • very cool (+1). Or even grep -q ERROR ex1 && truncate .... – JJoao Mar 9 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.