While Tom's answer will work very well in most situations, it may fail if you use a script with the -e flag. I mean, you are running a script with set -e at the very top. What for? Since Tom's answer relies on the exit status of the previous command, in this case grep -q , which will fail if it does not find the desired line, and therefore the whole script will fail. The -e flag documentation gives an idea of how to avoid this problem:
A failure does not end if a command that does not work is part of the list of commands immediately after some time or until the keyword, part of the test in the if statement, part of any command executed in && or || a list, with the exception of the command following the final && or ||, any command in the pipeline, but the last one, or if the return status of the commands is inverted with ..
So, one solution is to make the grep command a while condition command. However, since it launches mongodb with the --logappend option, the search string may appear as a result of a previous run. I coincided with the other guy responding with Tom's answer, and it works very well:
# Wait until mongo logs that it ready (or timeout after 60s) COUNTER=0 while !(nc -z localhost 27017) && [[ $COUNTER -lt 60 ]] ; do sleep 2 let COUNTER+=2 echo "Waiting for mongo to initialize... ($COUNTER seconds so far)" done
I find that using tomcat is the best solution because it really checks if there is something listening.
source share