Created
August 24, 2023 10:13
-
-
Save cmsj/d3de2a7e12f0804d50bf7c8fb742628f to your computer and use it in GitHub Desktop.
cmsj_docker_tool.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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