Home > front end >  Bash: how to listen the output of another running program
Bash: how to listen the output of another running program

Time:10-05

Say I have two bash scripts (p1.sh and p2.sh), representing two programs:

#!/bin/bash

echo "hello"
sleep 10s
echo "good morning"
sleep 10s
echo "goodbye !!"

And p2.sh:

#!/bin/bash

# listen to the output of p1's program
# if p1 gives "goodbye !!" output, echo "p1 said goodbye!"

The workflow is:

  1. Run p1.sh
  2. Get the pid of the p1 program
  3. Let p2.sh listen to the p1 process's output (instead of calling p1.sh inside of p2.sh), and judge p1's output.

How to realize it? Thanks!

CodePudding user response:

You can include either of the below lines in p2.sh. These command will exit to the next line only when the desired outcome in p1.sh is reached.

  1. If your intent is to check the content of the log, please try below

    tail -f <p1_log> |grep -m1 'goodbye'
    

    This command will exit when p1_log displays goodbye. This needs p2.sh started before p1.sh because p2.sh follows/watches p1.sh's log.

  2. If your intent to check if p1.sh has completed in p2.sh, you can use the tail command as below

    tail --pid=<p1_pid> -f <p1_log>
    

    This command will exit when p1 ends.

Happy to be corrected and learn.

CodePudding user response:

Pipe the output of p1.sh to a while read loop.

p1.sh | while read -r line; do
    if [ "$line" = "goodby !!" ]
    then echo "p1 said goodbye"
    fi
done
  • Related