Skip to content

Instantly share code, notes, and snippets.

@stephancasas
Created November 19, 2022 16:25
Show Gist options
  • Save stephancasas/e07f4e536ee0348fd3aba889d8586f61 to your computer and use it in GitHub Desktop.
Save stephancasas/e07f4e536ee0348fd3aba889d8586f61 to your computer and use it in GitHub Desktop.
Connect to an existing Docker container and start an interactive shell (terminal / tty).
dterm() {
# args as `[PROJECT_NAME] [SERVICE_NAME]` or `[CONTAINER_NAME]`
[ -z "$2" ] && CONTAINER_BASE_NAME="$1" || CONTAINER_BASE_NAME="${1}_${2}"
CONTAINER_NAME=$(docker ps --format "{{.Names}}" | grep ^${CONTAINER_BASE_NAME})
if [ $(printf "$CONTAINER_NAME" | wc -l) -gt 1 ]; then
echo "\e[1;31m[!] Multiple container names match \"$CONTAINER_BASE_NAME.\""
echo ">>> If project, add specificity as \`dockertty [PROJECT_NAME] [SERVICE_NAME]\`.\e[0m"
return
fi
# find container's installed shells
BIN_LS=$(docker exec "$CONTAINER_NAME" ls /bin)
if [ ! -z $(echo "$BIN_LS" | grep "^bash$") ]; then
TARGET_SHELL="bash"
else
if [ ! -z $(echo "$BIN_LS" | grep "^ash$" ) ]; then
TARGET_SHELL="ash"
else
TARGET_SHELL="sh"
fi
fi
docker exec -it "$CONTAINER_NAME" "/bin/${TARGET_SHELL}"
}
@stephancasas
Copy link
Author

I got tired of typing docker exec -it <container_full_name> /bin/ash, so I made this function to truncate keystrokes down to dterm <project> <service>.

Hooray.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment