Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store `docker run` command output in BASH variable

I'm having an issue storing the output of docker run -it -d -p 43211:3000 --name appname -h hostname -v $PWD/local_dir:/root/remote_dir repo/imagename in a BASH varibale. I tried `backticks`, I also tried running it like the official docs say BASH_VAR=$(docker run ...), I even tried storing the output in a file with docker run --...>$FILE_DESCRIPTOR, but no luck storing the error situation, the situation when the name is already used by another container, like so:

$ 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 the success situation, so I'm able to store in BASH_VAR the full container ID, upon running the application successfully, but unfortunately this solves only half the problem I'm facing.

Any help would be appreciated.

Thanks!

like image 688
Adrian Oprea Avatar asked Mar 15 '15 19:03

Adrian Oprea


People also ask

How do you assign the output of a command to a variable in a shell script?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do I run a docker container in bash?

In order to start a Bash shell in a Docker container, execute the “docker exec” command with the “-it” option and specify the container ID as well as the path to the bash shell. If the Bash is part of your PATH, you can simply type “bash” and have a Bash terminal in your container.

How do I pass an environment variable in docker run?

When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.


1 Answers

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 )
like image 117
franzisk Avatar answered Sep 19 '22 21:09

franzisk