Store `docker run` command output in BASH variable

2019-06-20 09:51发布

问题:

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!

回答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 select
select: select NAME [in WORDS ... ;] do COMMANDS; done
     Select words from a list and execute commands.