0

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!

IsaIkari
  • 1,002
  • 16
  • 31
  • You could execute p1 as `p1.sh|tee p1.out' and then use `tail -f p1.out` to monitor the output. This assumes that you mean by output to monitor _standard output_, and not _standard error_. – user1934428 Oct 05 '21 at 07:04
  • There are some weird and wonderful ideas here... https://stackoverflow.com/q/715751/2836621 – Mark Setchell Oct 05 '21 at 07:05

2 Answers2

1

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
BigHeadNelson
  • 73
  • 1
  • 4
0

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! But sorry I didn't make my question clear -- could it be listening to a process (a running program), instead of calling `p1.sh` inside `p2.sh`? Thanks! – IsaIkari Oct 05 '21 at 01:48
  • No, there's no way to attach to the output of an existing process. – Barmar Oct 05 '21 at 05:57