Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 754
Brad Avatar asked Aug 25 '11 21:08

Brad


People also ask

Is there a wait command in bash?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

How do I make bash script wait?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Does bash have a Continue statement?

The Bash continue statement resumes the following iteration in a loop or looping statement. The continue statement only has meaning when applied to loops. The integer value indicates the depth for the continue statement. By default, the integer is 1 and writing the number is not mandatory.


1 Answers

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.

like image 189
Ivin Avatar answered Oct 02 '22 18:10

Ivin