Home > Blockchain >  Bash script question: Why does it generate error in checking whether a variable exists?
Bash script question: Why does it generate error in checking whether a variable exists?

Time:12-03

I am confused by the problem of my bash script. I want to check if a docker container exists by first listing them and grep if the container name exists. But the script generates an error 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

CodePudding user response:

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

CodePudding user response:

I don't get what you want exactly but I think you meant you wanted to get Images names from the docker ps command I used awk to get the second option of output and prevent grep from getting wrong data from other fields then passed the result to grep and finally used $2>1 at the end which redirects stderr to stdout this will solve your issue.

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

IMAGE=$(docker ps | awk '{print $2}' | grep my-dev-image &2>1)
if [[ -z "$IMAGE" ]]; then
  echo "It is not there"
else
  echo "It is there"
fi

You can also use this command (am not and expert but it fixes this issue)

IMAGE=$(docker ps | awk '{print $2}' | grep aport ) || :;

UPDATE:

grep Exit status is 0 if any line is selected, 1 otherwise; if any error occurs and -q is not given, the exit status is 2

-z flag causes the test to check whether a string is empty. Returns true if the string is empty, false if it contains something.

  •  Tags:  
  • bash
  • Related