Skip to content

Instantly share code, notes, and snippets.

@jaydansand
Last active June 28, 2022 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydansand/29744bd44d6ea68611e430a401cb7d14 to your computer and use it in GitHub Desktop.
Save jaydansand/29744bd44d6ea68611e430a401cb7d14 to your computer and use it in GitHub Desktop.
Launch a shell in a Docker container/image
#!/bin/sh
# Author: Jay Dansand
# URL: https://gist.github.com/jaydansand/29744bd44d6ea68611e430a401cb7d14
# Date: May 29 2019, modified June 28 2022
CONTAINER="$1"
if [ -z "$CONTAINER" ]; then
echo "Usage: `basename $0` container|service [shell command]"
echo " Executes shell command (default bash || sh) in a container. If CONTAINER"
echo " is not a running Docker container (appearing in 'docker ls -a') then it"
echo " will be tested as a docker-compose service or run as an image name."
exit 1
fi
SHELLCMD="$2"
if [ -z "$SHELLCMD" ]; then
SHELLCMD='sh -c "if [ `which bash` ]; then bash; else sh; fi"';
fi
# Is it a running container (i.e. use "exec") or an image?
RESULTS=`docker container ls -a 2>/dev/null | cut -f1 -s -d ' ' | tail -n +2 | grep -ci "^$CONTAINER" 2>/dev/null`
RUNNING="$?"
if [ "$RUNNING" -eq 0 ]; then
# It's running, use exec.
if [ "$RESULTS" != "1" ]; then
echo "Given container string matches more than one running container (results: $RESULTS)"
exit 2
fi
echo "Executing shell in $CONTAINER..."
docker exec -it "$CONTAINER" sh -c "$SHELLCMD"
else
# Is it docker-compose-based?
# In theory w/label com.docker.compose.service=$CONTAINER.
# docker-compose ps --services | grep -P "^${CONTAINER}\$"
SERVICE=`docker-compose ps --services 2>/dev/null | grep -P "^${CONTAINER}\$" 2>/dev/null`
IS_SERVICE="$?"
if [ "$IS_SERVICE" -eq 0 ]; then
echo "Executing shell in service \"$SERVICE\" via docker-compose..."
docker-compose exec "$SERVICE" sh -c "$SHELLCMD"
else
# It's not running, start an image.
echo "Running shell in image $CONTAINER..."
# Use --entrypoint to override any defined automatic command baked into the
# image. It's a bit roundabit, but we use "sh -c" to launch our command.
docker run -it --rm --entrypoint="sh" "$CONTAINER" -c "$SHELLCMD"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment