1

I am trying to check whether a docker container exists using grep.

The following script signals an error exit during running when IMAGE is empty and is fine when IMAGE is set. I can't find out the cause.

#!/usr/bin/env bash
set -e

IMAGE=$(docker ps | grep my-dev-image)

if [[ -z "$IMAGE" ]]; then
  echo "It is not there"
else
  echo "It is there"
fi
3
  • 3
    What's the error? Commented Dec 3, 2021 at 2:16
  • Relevant: BashFAQ #105 - Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected? -- if in a hurry, be sure to read the exercises section. Commented Dec 3, 2021 at 4:37
  • 1
    The script generates an error exit and stops because of set -e. Commented Dec 3, 2021 at 6:21

1 Answer 1

4

When you use set -e in a script the shell will exit whenever a command fails. It interacts badly with your grep call because grep exits with an error code if it doesn't find a match. If grep fails then the entire IMAGE=$(...) assignment fails and the script exits instead of setting IMAGE to an empty string.

You can fix this by ensuring the assignment always succeeds. A common idiom for this is to append || :. Adding || cmd will run cmd whenever the command on the left fails. And : is a command that always succeeds. (Yes, it's a command name consisting of a single colon. Strange, but it's a legal identifier.)

IMAGE=$(docker ps | grep my-dev-image) || :

Alternatively, you could check grep's exit code directly by using it in the if statement. This is what I would do if I didn't care about grep's output:

if docker ps | grep -q my-dev-image; then
    echo "It is there"
else
    echo "It is not there"
fi
Sign up to request clarification or add additional context in comments.

Comments

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.