Shell: Check if docker container is existing

$? isn't a string but the exit status of sudo (in this case). To use that properly, compare it against zero with -gt, or use if (( $? )) (in a shell like bash or ksh93 that does arithmetic evaluation with (( ... ))).

If sudo docker images -q nginx gives you a string if the container exists and nothing if it doesn't, then you may store that in a variable and see if it's empty or not:

result=$( sudo docker images -q nginx )

if [[ -n "$result" ]]; then
  echo "Container exists"
else
  echo "No such container"
fi

I tried docker images -q {Image Name} as suggested in the "best answer" but it only returned the ID of the Image, not of the container. No matter if the container is running or not, it always returns the Image ID.

If you want to know whether or not the CONTAINER is running, you need to apply the following command:

docker ps -q -f name={container Name}

If the container exists, the container ID is returned. An empty string comes back if it is stopped or not existing.

Tags:

Shell Script