bashdockerloopsalpine-linuxconsole-output

Loop trough docker output until I find a String in bash


I am quite new to bash (barely any experience at all) and I need some help with a bash script.

I am using docker-compose to create multiple containers - for this example let's say 2 containers. The 2nd container will execute a bash command, but before that, I need to check that the 1st container is operational and fully configured. Instead of using a sleep command I want to create a bash script that will be located in the 2nd container and once executed do the following:

  1. Execute a command and log the console output in a file
  2. Read that file and check if a String is present. The command that I will execute in the previous step will take a few seconds (5 - 10) seconds to complete and I need to read the file after it has finished executing. I suppose i can add sleep to make sure the command is finished executing or is there a better way to do this?
  3. If the string is not present I want to execute the same command again until I find the String I am looking for
  4. Once I find the string I am looking for I want to exit the loop and execute a different command

I found out how to do this in Java, but if I need to do this in a bash script.

The docker-containers have alpine as an operating system, but I updated the Dockerfile to install bash.

I tried this solution, but it does not work.

#!/bin/bash

[command to be executed] > allout.txt 2>&1

until 
  tail -n 0 -F /path/to/file | \
  while read LINE
  do
    if echo "$LINE" | grep -q $string
    then
      echo -e "$string found in the console output"
  fi
  done
do
    echo "String is not present. Executing command again"
    sleep 5
    [command to be executed] > allout.txt 2>&1
done

echo -e "String is found"

Solution

  • Just:

    while :; do
       # 1. Execute a command and log the console output in a file
       command > output.log
       # TODO: handle errors, etc.
       # 2. Read that file and check if a String is present.
       if grep -q "searched_string" output.log; then
           # Once I find the string I am looking for I want to exit the loop
           break;
       fi
       # 3. If the string is not present I want to execute the same command again until I find the String I am looking for
       # add ex. sleep 0.1 for the loop to delay a little bit, not to use 100% cpu
    done
    # ...and execute a different command
    different_command
    

    You can timeout a command with timeout.

    Notes: