#!/bin/bash tm=`date +%Y%m%d-%H%M%S` echo "=====================================================" echo "Starting <${tm}>" # set constant variables pmodule=zuul pdelete="" show_usage="args: [-m, -d]\ [--pmodule, --pdelete=]" GETOPT_ARGS=`getopt -o m:d:s: -al pmodule:,pdelete: -- "$@"` # echo "$GETOPT_ARGS" eval set -- "$GETOPT_ARGS" while [ -n "$1" ] do case "$1" in -m|--pmodule) pmodule=$2; shift 2;; -d|--pdelete) pdelete=$2; shift 2;; --) break ;; *) echo $1,$2,$show_usage; break ;; esac done if [[ -z $pmodule ]]; then echo $show_usage exit 0 fi # get container sn sn=`sudo docker ps -a | grep ${pmodule} | wc -l` echo "Has ${sn} container of ${pmodule}" # get container id # container_id=`sudo docker ps -a | grep ${pmodule} | awk -F '[ ]+' 'NR==1{print $1}'` all_container_id=`sudo docker ps -a | grep ${pmodule} | awk -F '[ ]+' '{print $1}' | tr "\n" " " | sed -e 's/,$/\n/'` echo "All container id is ${all_container_id}" gt_container_id=`sudo docker ps -a | grep ${pmodule} | awk 'NR>1' | awk -F '[ ]+' '{print $1}' | tr "\n" " " | sed -e 's/,$/\n/'` echo "Great 1 container id is ${gt_container_id}" # get image name isn=`sudo docker images | grep ${pmodule} | wc -l` echo "Has ${isn} image of ${pmodule}" all_image_id=`sudo docker images | grep ${pmodule} | awk -F '[ ]+' '{print $3}' | tr "\n" " " | sed -e 's/,$/\n/'` echo "All image id is ${all_image_id}" gt_image_id=`sudo docker images | grep ${pmodule} | awk 'NR>1' | awk -F '[ ]+' '{print $3}' | tr "\n" " " | sed -e 's/,$/\n/'` echo "Great 1 images id is ${gt_image_id}" if [ ! -n "$pdelete" ] && [ -n "$gt_container_id" ]; then echo "stop container ${gt_container_id}" sudo docker stop ${gt_container_id} echo "remove container ${gt_container_id}" sudo docker rm -f ${gt_container_id} elif [ -n "$pdelete" ] && [ -n "$all_container_id" ]; then echo "stop container ${all_container_id}" sudo docker stop ${all_container_id} echo "remove container ${all_container_id}" sudo docker rm -f ${all_container_id} else echo "Nothing to do." fi if [ ! -n "$pdelete" ] && [ -n "$gt_image_id" ]; then echo "remove image ${gt_image_id}" sudo docker rmi -f ${gt_image_id} elif [ -n "$pdelete" ] && [ -n "$all_image_id" ]; then echo "remove image ${all_image_id}" sudo docker rmi -f ${all_image_id} else echo "Nothing to do." fi