0

How can one run docker commands from a bash (sh) script? I am trying to run:

#!/bin/bash
container= $(docker ps --format "{{.ID}} {{.Names}}" -a | grep testServer | awk '/'$imid'/ { print $1 }');
echo $container

but I get a blank for the container.

TIA

4
  • What is $imid? Commented May 15, 2017 at 16:52
  • Sorry - it is a leftover. The goal was to get the container name. Commented May 15, 2017 at 16:53
  • 1
    I'd try with a simple docker command hardcoded until you get the printing working as expected. Then start doing clever grep/awk magic. Commented May 15, 2017 at 16:54
  • 1
    Do you really have a space between = and $ in your code, or is that a typo? Commented May 15, 2017 at 17:05

2 Answers 2

1

It looks like the container id is printed to sterr and the $() construct only captures stdout.

As per this comment, you can use 2>&1 to redirect stderr to stdout, but I'm not quite sure how to work that into your snippet with the grep/awk chaining going on.

Sign up to request clarification or add additional context in comments.

Comments

0

Did some testing - as suggested - and found that the following works from bash.

#!/bin/bash
container=$(docker ps --format "{{.ID}} {{.Names}}" -a | grep testServer  | awk '/'$imid'/ { print $1 }')
echo $container
if [[ $container = *[!\ ]* ]]; then
        echo "found something";
else
        echo "DID NOT find anything";
fi

I guess I just had to play around with it some more.

2 Comments

Maybe a saner way to do it. Unless you need to capture the exact container id to stop or kill it later.
Yes - I need to use the ID for later - so it works as needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.