Skip to content

Instantly share code, notes, and snippets.

@weshouman
Last active May 4, 2024 09:58
Show Gist options
  • Save weshouman/2c162cb6b71594f6bd3febe5eb5089a3 to your computer and use it in GitHub Desktop.
Save weshouman/2c162cb6b71594f6bd3febe5eb5089a3 to your computer and use it in GitHub Desktop.
Remove containers of a given image name
#!/usr/bin/env bash
remove_containers_by_image() {
local image_name=""
local dry_run=false
# Local function to display help
display_help() {
echo "Usage: ${FUNCNAME[1]} [-h|--help] [-n|--dry-run] [-i|--image IMAGE_NAME]"
echo ""
echo "Options:"
echo " -h, --help Display this help message and exit"
echo " -n, --dry-run Display the commands that would be executed without actually running them"
echo " -i, --image Specify the Docker image name whose containers should be removed"
echo ""
echo "If no image is specified, a selection menu will appear for choosing an image from existing containers."
echo "This script is deliberately avoiding usage of -f while removing containers"
}
# Parse parameters
while [[ "$#" -gt 0 ]]; do
case "$1" in
-h|--help)
display_help
return 0
;;
-n|--dry-run)
dry_run=true
shift
;;
-i|--image)
image_name="$2"
shift 2
;;
*)
echo "Unknown option: $1"
display_help
return 1
;;
esac
done
# If no image name is provided, list available images from containers and ask user to select one
if [[ -z "$image_name" ]]; then
echo "Select an image from the following list:"
local images=$(docker ps -a --format '{{.Image}}' | sort -u)
select img in $images; do
if [[ -n "$img" ]]; then
image_name="$img"
break
else
echo "Invalid selection. Try again."
fi
done
fi
# Find all containers with the specified image
local container_ids=$(docker ps -a --filter "ancestor=$image_name" --format "{{.ID}}")
if [[ -z "$container_ids" ]]; then
echo "No containers found for image: $image_name"
return 1
fi
# Display or execute container removal
if [[ "$dry_run" == true ]]; then
echo "Dry run: Removing containers of $image_name using "
echo "docker rm $container_ids"
else
echo "Removing containers for image: $image_name"
docker rm $container_ids
fi
}
# Example usage:
# remove_containers_by_image -i "ubuntu:latest"
# remove_containers_by_image --dry-run --image "nginx"
# remove_containers_by_image (then select image interactively)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment