13

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.

1
  • Are you developing the server? Because a fork once it is initialized would be much easier... Sep 22, 2016 at 2:55

1 Answer 1

10

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 "$@"
1
  • 1
    This is great, thanks; I think after basename it should say $0 not just 0, though. Jun 7, 2022 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .