You can do it this way:
CONTAINER_NAME='mycontainername'
CID=$(docker ps -q -f status=running -f name=^/${CONTAINER_NAME}$)
if [ ! "${CID}" ]; then
echo "Container doesn't exist"
fi
unset CID
or
if [ ! "$(docker ps -q -f name=<name>)" ]; then
if [ "$(docker ps -aq -f status=exited -f name=<name>)" ]; then
# cleanup
docker rm <name>
fi
# run your container
docker run -d --name <name> my-docker-image
fi
For reference:
Docker ps [OPTIONS]
Options
--all , -a Show all containers (default shows just running)
--filter , -f Filter output based on conditions provided
--format Pretty-print containers using a Go template
--last , -n -1 Show n last created containers (includes all States)
--Latest , -l Show the Latest created container (includes all States)
--no-trunc Don’t truncate output
--quiet , -q Only display Numeric Ids
--size-s Display total file
Very well, you could edit your answer and explain the parameter
-a
? For future reference.– NoobSaibot
You’re done, my friend, a hug
– Thiago Loureiro
The condition is not working ! It is returning
not found
– NoobSaibot
@wmsouza edited the answer and put more alternatives, if you can test abs.
– Thiago Loureiro