Run the `docker run` command in the BASH variable

I have a problem saving output docker run -it -d -p 43211:3000 --name appname -h hostname -v $PWD/local_dir:/root/remote_dir repo/imagename in varibale BASH. I tried "backticks", I also tried to run it, as official docs BASH_VAR=$(docker run ...) , I even tried to save the output to a file using docker run --...>$FILE_DESCRIPTOR , but failed save the situation with the error, the situation when the name is already in use by another container, for example:

$ FATA[0000] Error response from daemon: Conflict. The name "appname" is already in use by container 7c84d8d703c8. You have to delete (or rename) that container to be able to reuse that name.

I want to say that it works for success, so I can store the full container identifier in BASH_VAR when the application starts successfully, but, unfortunately, this solves only half of the problem that I encountered.

Any help would be greatly appreciated.

Thanks!

+7
source share
3 answers

You need to fix the standard error and save it in a variable.

Using

 BASH_VAR=$(command) 

or

 BASH_VAR='command' 

captures standard output, not standard error.

This is the correct syntax for storing standard error messages in a variable:

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

You can use the while loop to read each line of output as it is created and do something with it.

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

Alternatively, if you are writing an interactive script, you can check the select bash inline

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

you may need to exit the while loop, but this is possible, for 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" 
0
source

Source: https://habr.com/ru/post/1215404/


All Articles