Store `docker run` command output in BASH variable Store `docker run` command output in BASH variable docker docker

Store `docker run` command output in BASH variable


What you need is to capture standard error and store it in a variable.

Using

BASH_VAR=$(command)

or

BASH_VAR=`command`

will capture standard output and not standard error.

This is the right syntax to store standard error messages in a variable:

BASH_VAR=$( { command; } 2>&1 )


You could use a while loop to read each line of output as it's produced and do something with it that way.

while read -r line_of_output; do  echo "line: $line_of_output"done < <(docker ... 2>&1)

Also, if you're writing an interactive script, you might want to check out the select bash builtin

$ help selectselect: select NAME [in WORDS ... ;] do COMMANDS; done     Select words from a list and execute commands.


you might need to break out of the while loop , but yes it is possible, example:

  MYSQL_IMAGE_NAME='mysql/mysql-server:5.7'  docker pull "$MYSQL_IMAGE_NAME"  docker images  docker run --name=mysql-server-container -d "$MYSQL_IMAGE_NAME"  docker container ls  while read -r line ; do     GENERATED_PWD="$(echo $line | grep 'GENERATED ROOT PASSWORD'|awk '{print $5}')"     test -z $GENERATED_PWD || break  done < <(docker logs --tail 3000 --follow mysql-server-container)  echo "GENERATED_PWD: $GENERATED_PWD"