5

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.

  • Are you developing the server? Because a fork once it is initialized would be much easier... – Alexis Wilke Sep 22 '16 at 2:55
1

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 "$@"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.