Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

How can I wait for certain output from a process then continue in Bash?

I'm trying to write a bash script to do some stuff, start a process, wait for that process to say it's ready, and then do more stuff while that process continues to run. The issue I'm running into is finding a way to wait for that process to be ready before continuing, and allowing it to continue to run.

In my specific case I'm trying to setup a PPP connection. I need to wait until it has connected before I run the next command. I would also like to stop the script if PPP fails to connect. pppd prints to stdout.

In psuedo code what I want to do is:

[some stuff]
echo START

[set up the ppp connection]
pppd <options> /dev/ttyUSB0
while 1
  if output of pppd contains "Script /etc/ppp/ipv6-up finished (pid ####), status = 0x0"
    break
  if output of pppd contains "Sending requests timed out"
    exit 1

[more stuff, and pppd continues to run]
echo CONTINUING

Any ideas on how to do this?

question from:https://stackoverflow.com/questions/7197527/how-can-i-wait-for-certain-output-from-a-process-then-continue-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had to do something similar waiting for a line in /var/log/syslog to appear. This is what worked for me:

FILE_TO_WATCH=/var/log/syslog
SEARCH_PATTERN='file system mounted'

tail -f -n0 ${FILE_TO_WATCH} | grep -qe ${SEARCH_PATTERN}

if [ $? == 1 ]; then
    echo "Search terminated without finding the pattern"
fi

It pipes all new lines appended to the watched file to grep and instructs grep to exit quietly as soon as the pattern is discovered. The following if statement detects if the 'wait' terminated without finding the pattern.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...