Skip to content

Instantly share code, notes, and snippets.

@kamermans
Last active June 12, 2022 21:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamermans/b3abd6079dfd33427c9232f78b640d61 to your computer and use it in GitHub Desktop.
Save kamermans/b3abd6079dfd33427c9232f78b640d61 to your computer and use it in GitHub Desktop.
Bash functions for dealing with Docker containers in an unknown state (starting, stopping, removing, checking if they exist, etc)
# Helper functions for dealing with Docker containers
# Returns "missing", "stopped" or "running"
get_container_state() {
local CONTAINER_NAME=$1
# Faster check to see if the container *might* exist
CONTAINER_MISSING=$(container_does_not_exist "$CONTAINER_NAME")
if [[ $CONTAINER_MISSING = "true" ]]; then
echo -n "missing"
return
fi
# Returns "true" if running, "false" if stopped, or neither if non-existent
local CONTAINER_STATE=$(docker inspect -f {{.State.Running}} "$CONTAINER_NAME" 2>&1)
if [[ $CONTAINER_STATE = "true" ]]; then
echo -n "running"
return
elif [[ $CONTAINER_STATE = "false" ]]; then
echo -n "stopped"
return
fi
echo -n "missing"
return
}
# This method can quickly determine if the container DOES NOT exist, but
# since it matches CONTAINER_NAME as a substring, it can't prove that the
# container DOES exist.
# Returns "true" if definitely missing, "false" if it *could* exist
container_does_not_exist() {
local CONTAINER_ID=$(docker ps -q -f status=running -f name=$CONTAINER_NAME 2>&1)
if [[ -z $CONTAINER_ID ]]; then
echo -n "true"
return
fi
echo -n "false"
}
stop_container() {
local CONTAINER_NAME=$1
echo -n "Stopping container: "
docker stop "$CONTAINER_NAME"
}
remove_container() {
local CONTAINER_NAME=$1
echo -n "Removing container: "
docker rm -vf "$CONTAINER_NAME"
}
remove_container_if_exists() {
local CONTAINER_NAME=$1
local CONTAINER_STATE=$(get_container_state "$CONTAINER_NAME")
if [[ $CONTAINER_STATE = "missing" ]]; then
return
fi
if [[ $CONTAINER_STATE = "running" ]]; then
stop_container "$CONTAINER_NAME"
CONTAINER_STATE="stopped"
fi
if [[ $CONTAINER_STATE = "stopped" ]]; then
remove_container "$CONTAINER_NAME"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment