Results 1 to 5 of 5

Thread: bash: check if file size is zero before doing some action

  1. #1
    Join Date
    Jul 2014
    Beans
    340

    Question bash: check if file size is zero before doing some action

    Hi all,
    I'm sending some log to my inbox on regular basis using crontab. Sometimes log is empty and I would like to skip it in this case if possible.
    Code:
    59 0 * * * rm /tmp/rejectlog_filtered.txt; less /var/log/exim4/rejectlog | grep -v "junkemailfilter" > /tmp/rejectlog_filtered.txt; mpack -s "rejectlog_filtered.txt" /tmp/rejectlog_filtered.txt user@example.com
    
    Another question is, how do I send mentioned log file as message body instead of attachment? (less important for me, but still would like to solve)
    Please advise.

  2. #2
    Join Date
    Nov 2011
    Location
    /dev/root
    Beans
    Hidden!

    Re: bash: check if file size is zero before doing some action

    Test with test -s

    Code:
    test -s filename
    If size=0, the test returns 1, otherwise if size>0 test returns 0.

    You find more details about test in bash by the command

    Code:
    help test

  3. #3
    Join Date
    Jul 2014
    Beans
    340

    Re: bash: check if file size is zero before doing some action

    Hi sudodus,
    Thanks, I tested it and it should work for me.
    I don't know when it returns 0 and when 1, but below command returns size=0 properly (if file is empty indeed) :
    Code:
    $ if test -s /tmp/test.txt; then echo -e "size>0"; else echo -e "size=0"; fi
    size=0
    Upd:
    Code:
    $ less /home/user/rejectlog_email.sh
    if [ -f "/tmp/rejectlog_filtered.txt" ]; then rm /tmp/rejectlog_filtered.txt; fi
    
    less /var/log/exim4/rejectlog | grep -v "junkemailfilter" > /tmp/rejectlog_filtered.txt
    
    if test -s /tmp/rejectlog_filtered.txt; then mpack -s "some subject" /tmp/rejectlog_filtered.txt user@example.com; fi
    Last edited by slickymaster; December 10th, 2019 at 05:42 PM. Reason: code tags

  4. #4
    Join Date
    Nov 2011
    Location
    /dev/root
    Beans
    Hidden!

    Re: bash: check if file size is zero before doing some action

    Returning zero means true (or success) while 1 means false (or failure). I think you got it right.

    Please notice that [ something ] is the same as test something

  5. #5
    Join Date
    Jul 2014
    Beans
    340

    Re: bash: check if file size is zero before doing some action

    Thanks sudodus.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •