0

I'm building a bash script to send an email based off the last command. I seem to be having difficulties. Outside of a script the command works fine but when putting it in script it doesn't give the desired outcome.

Here is snippet of script:

grep -vFxf /path/to/first/file /path/to/second/file > /path/to/output/file.txt 
if [ -s file.txt ] || echo "file is empty";
then
          swaks -t "[email protected]" -f "[email protected]" --header "Subject: sample" --body "Empty"
else
          swaks -t "[email protected]" -f "[email protected]" --header "subject: sample" --body "Not Empty"
fi

I ran the commands outside of script and I can see that there is data but when I add the commands within script I get the empty output. Please advise . Thank you in advance .

2
  • Are [ -s file.txt ] and /path/to/output/file.txt the same? (you should always double-quote within [...] -- granted with file.txt it makes no difference, but if it is a variable - double-quote) Please provide A Minimal, Complete, and Verifiable Example (MCVE). Commented Mar 26, 2018 at 20:48
  • @DavidC.Rankin Yes, those two files are the same . Thanks, I'll update with the double quotes . Commented Mar 26, 2018 at 20:52

1 Answer 1

3

Your condition will always be true, because if [ -s file.txt ] fails, the exit status of the ||-list is the exit status of echo, which is almost guaranteed to be 0. You want to move the echo out of the condition and into the body of the if statement. (And to simplify further, just set the body to a variable and call swaks after the if completes.

if [ -s file.txt ];
then
    body="Not Empty"
else
    echo "file is empty"
    body="Empty"
fi
swaks -t "[email protected]" -f "[email protected]" --header "subject: sample" --body "$body"

If the only reason you create file.txt is to check if it is empty or not, you can just put the grep command directly in the if condition:

if grep -vFxfq /atph/to/first/file /path/to/second/file; then
    body="Not Empty"
else
    echo "No output"
    body="Empty"
fi

swaks -t "[email protected]" -f "[email protected]" --header "subject: sample" --body "$body"
Sign up to request clarification or add additional context in comments.

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.