Search code examples
bashshellubuntush

how to trigger a mail based on first shell echo result?


i have two shell scripts, one is checking_file.sh, second one is mailing.sh.

checking_file.sh


#!/bin/bash

filepath="/home/documents/hello.txt"

if [ -f "$filepath" ]; then
   echo "file exists"
else
   echo "file not exists"

fi

mailing.sh


#!/bin/bash

output=$(/home/documents/checking_file.sh)

if [ "$output" = "file not exists" ]; then
   echo "trigger mail to developer"
else
  echo "file is available in time no mail needed"
fi

mailing.sh should execute at last. both are different scripts.

i used chmod u+r+X /home/documents/checking_file.sh in mailing.sh, but mailing.sh should execute last. mailing.sh should read the checking_file.sh, its should not execute checking_file.sh shell


Solution

  • Based on OP's comments:

    • mailing.sh should not call checking_file.sh but should 'read' the output from checking_file.sh
    • one approach would be to have checking_file.sh write its output to a file ...
    • modify checking_file.sh to write its output to a file
    • modify mailing.sh to read the contents of said file

    Making minimal changes to OP's current code:

    $ cat checking_file.sh
    #!/bin/bash
    
    filepath="/home/documents/hello.txt"
    
    if [ -f "$filepath" ]; then
       echo "file exists"
    else
       echo "file not exists"
    fi > /home/documents/checking_file.out               # write output to file
    
    
    
    $ cat mailing.sh
    #!/bin/bash
    
    #output=$(/home/documents/checking_file.sh)
    output=$(cat /home/documents/checking_file.out)      # read output from file
    
    if [ "$output" = "file not exists" ]; then
       echo "trigger mail to developer"
    else
       echo "file is available in time no mail needed"
    fi
    

    NOTES:

    • OP may want to add some logic to mailing.sh to verify checking_file.out actually exists
    • OP may want to add some logic to mailing.sh to remove/rename checking_file.out so that a repeated run of mailing.sh does not process the same checking_file.out a second time

    Addressing OP's comment/question about not modifying checking_file.sh ...

    With no modifications to checking_file.sh we can have the invocation direct all output to a file, eg:

    $ /home/documents/checking_file.sh > /home/documents/checking_file.out 2>&1