Skip to content

Instantly share code, notes, and snippets.

@cmsj
Created August 24, 2023 10:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
cmsj_docker_tool.sh
#!/bin/bash
# A simple tool for managing docker containers
# Drop this in your path somewhere and chmod +x it, then create symlinks to it with the names:
# clog - show the logs for a container
# cblip - restart a container and then show its logs
# cgo - run a command inside a container (defaults to /bin/sh)
# Usage for each is: <command> CONTAINER_NAME
CMD="$(basename $0)"
if [ "$1" == "" ]; then
echo "Usage: ${CMD} CONTAINER_NAME"
exit 1
fi
SEARCH_TERM="$1"
RESULT=""
function find_container() {
# First look for containers that start with the given name
RESULT="$(docker ps -a --format "{{.Names}}" | grep "^${SEARCH_TERM}$" | head -1)"
if [ "${RESULT}" == "" ]; then
# If no exact match, look for containers that contain the given name
RESULT="$(docker ps -a --format "{{.Names}}" | grep "${SEARCH_TERM}" | head -1)"
fi
echo "${RESULT}"
}
RESULT=$(find_container "${SEARCH_TERM}")
if [ "${RESULT}" == "" ]; then
echo "Container ${SEARCH_TERM} not found."
exit 1
fi
if [ "${CMD}" == "cblip" ]; then
docker restart "${RESULT}" &
CMD="clog" # Reuse the clog command below to show the logs
fi
if [ "${CMD}" == "clog" ]; then
journalctl -fb CONTAINER_NAME="${RESULT}"
elif [ "${CMD}" == "cgo" ]; then
shift 1
ARGS="${*:-/bin/sh}"
docker exec -ti "${RESULT}" ${ARGS}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment