Bash – Wait for Foreground Process to Emit String, Then Send to Background

bashprocessshell-script

With a bash script I'm trying to start a process, wait for it to write a specific string to stdout (i.e. 'Server Initialized'), and then send it to the background and continue with the script. Even better if once 'Server Initialized' is printed the process output is ignored (redirected to /dev/null?)

As a hack right now I'm waiting 10 seconds and assuming the server has started.

( ./long_running_process ) > /dev/null 2>&1 &
# sleep 10
echo 'I run after long_running_process prints "Server Initialized"

Bonus points if, after some timeout, the search string hasn't appeared then exit with an error status code.

Best Answer

The idea is to run the server in the background and then grep its output as long as the expected string has appeared 'Something 3' ('Server Initialized' in your case)

#!/bin/bash

main()  
{
    output=$(mktemp "${TMPDIR:-/tmp/}$(basename 0).XXX")
    server &> $output &
    server_pid=$!
    echo "Server pid: $server_pid"
    echo "Output: $output"
    echo "Wait:"
    until grep -q -i 'Something 3' $output
    do       
      if ! ps $server_pid > /dev/null 
      then
        echo "The server died" >&2
        exit 1
      fi
      echo -n "."
      sleep 1
    done
    echo 
    echo "Server is running!" 
}

server() 
{       
    i=0
    while true; do
      let i++
      echo "Something $i"  
      sleep 1
    done
}

main "$@"
Related Question