Skip to content

Instantly share code, notes, and snippets.

@huaxlin
Created August 11, 2022 03:20
Show Gist options
  • Save huaxlin/22fe8d48dfc691ea99ae4a23bb56c8b8 to your computer and use it in GitHub Desktop.
Save huaxlin/22fe8d48dfc691ea99ae4a23bb56c8b8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -e
help()
{
echo "Usage: $0 [[-c | --container]"
echo " --]"
echo ""
echo "Script Options:"
echo " --container, -c required"
echo " the name of container to be deleted"
echo " --"
echo " A seperator between script options and commands"
exit 2
}
SHORT=c:,h
LONG=container:,help
OPTS=$(getopt --alternative --name delete_container --options $SHORT --longoptions $LONG -- "$@")
VALID_ARGUMENTS=$# # Returns the count of arguments that are in short or long options
if [ "$VALID_ARGUMENTS" -eq 0 ]; then
help
fi
eval set -- "$OPTS"
while :
do
case "$1" in
-c | --container )
CONTAINER="$2"
shift 2
;;
-h | --help)
help
;;
--)
shift;
break
;;
*)
echo "Unexpected option: $1"
help
;;
esac
done
container_cnt=$(docker ps -a | grep "$CONTAINER" | wc -l)
echo "Existing $CONTAINER count: $container_cnt"
if [ $container_cnt -gt 0 ];
then
echo "Delete container($CONTAINER):"
docker ps -a | \
tail -n +2 | \
grep "$CONTAINER" | \
awk '{print $1}' | \
xargs docker rm -f
if [ ! $? -eq 0 ];
then
echo "Error in delete container!"
fi
else
echo "Container not exist, not need to delete."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment